Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 644
Griffin Avatar asked Dec 12 '22 13:12

Griffin


1 Answers

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/

like image 154
Eric Z Avatar answered Dec 26 '22 13:12

Eric Z