C++ copying a string array[] to a vector

2019-02-23 11:36发布

问题:

So i'm making this class with a member function "insert" to copy from a string array to the classes contents which is a vector array.

This abort error keeps popping up saying i'm going past the Vector end, but i don't understand why....

Here's the code:

/////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////      Map class   /////////////////////
class Map
{
private:
///////////////////////////////////////////     Map Variables ///////////////
    string _name;
    vector <string> _contents;

public:
    Map(string name){_name = name;
                     _contents.reserve(56);};
    ~Map(){};
    string getName()
    {
    return _name;
    };

    vector <string> getContents()
    {
        return _contents;
    };

///////////////////////////////////////////     Insert  ////////////////////////
            //  string* to an array of 56 strings;
    bool Insert(string* _lines_)
    {

    for (int I = 0; I < 3; I++)
    {
        _contents[I] = _lines_[I];
    }
        return true;
    };


};

If you need any more info just ask! Thanks!

回答1:

Actually, you don't need copy them yourself. You can use std::vector::assign to convert a c-style array to an std::vector.

vector::assign

Assigns new content to the vector object, dropping all the elements contained in the vector before the call and replacing them by those specified by the parameters.

Example

string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector;
sVector.assign(sArray, sArray+3);
        ^ ok, now sVector contains three elements, "aaa", "bbb", "ccc"

More details

http://www.cplusplus.com/reference/stl/vector/assign/



回答2:

Use std::copy as:

#include <algorithm> //for std::copy
#include <iterator>  //for std::back_inserter

std::copy(_lines_, _lines_ + count, std::back_inserter(_contents));

where count is the total number of strings in the array. If the total number of strings is 56, the count should be 56, not 55 (if you want all strings to be copied to _contents).



回答3:

The vector doesn't have a size (just some space reserveed).

You either have to resize() the vector, or use push_back() to add the new elements.



回答4:

You should resize vector <string> _contents before you can add any elements using the subscript [] operator.

Also: provide a default constructor your Map class.



回答5:

  1. You're not supposed to use underscore prefixed identifiers
  2. Assign _name in the initializer list: Map(string name) : _name(name) {
  3. _contents has enough capacity for 56 elements but has no actual elements. You should either resize it (_contents.resize(56);), add elements to it in the Insert method (_contents.push_back(_lines_[I]);), or construct it with enough capacity (add , _contents(56) to the initializer list).