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!

+4
source share
5 answers

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

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

+8
source

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 ).

+2
source

The vector has no size (only some reserve ed space).

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

+1
source

You must resize the vector <string> _contents before adding any elements using the subscript [] operator.

Also: provide a default constructor for your Map class.

+1
source
  • You must not use underscore identifiers
  • Assign _name to the initializer list: Map(string name) : _name(name) {
  • _contents has enough capacity for 56 elements, but does not have actual elements. You must either resize it ( _contents.resize(56); ), add elements to it in the Insert method ( _contents.push_back(_lines_[I]); ), or build it with sufficient capacity (add , _contents(56) in list of initializers).
+1
source

All Articles