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!
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
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
).
The vector doesn't have a size (just some space reserve
ed).
You either have to resize()
the vector, or use push_back()
to add the new elements.
You should resize vector <string> _contents
before you can add any elements using the subscript [] operator.
Also: provide a default constructor your Map class.
_name
in the initializer list: Map(string name): _name(name) {
_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).It is now much simpler. (C++11)
string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector (sArray, sArray + 3);
No copy, assign is need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.