C ++ copy string array [] to vector <string>
So, I am making this class with the "insert" member function to copy from an array of strings to the contents of the classes, which is a vector array.
This interrupt error continues to pop up, saying that I am walking past the end of the vector, but I donβt understand why ....
Here is 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 more information, just ask! Thanks!
Actually, you do not need to copy them yourself. You can use std::vector::assign to convert a c-style array to std::vector .
vector :: assignee
Assigns new content to a vector object, discarding all elements contained in the vector before the call, and replacing them with 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
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 rows in the array. If the total number of lines is 56 , count should be 56 , not 55 (if you want all lines to be copied to _contents ).
- You must not use underscore identifiers
- Assign
_nameto the initializer list:Map(string name) : _name(name) { _contentshas enough capacity for 56 elements, but does not have actual elements. You must either resize it (_contents.resize(56);), add elements to it in theInsertmethod (_contents.push_back(_lines_[I]);), or build it with sufficient capacity (add, _contents(56)in list of initializers).