Hey, the basic idea is to concatanate two vectors in a big one.
Unfortunately I get the error:
terminate called after throwing an instance of 'std::length_error'
what(): vector::_M_range_insert
the Idea is to create one big vector in ChildB collector which contains the vector vec of ChildA child1 and child2.
Here I have written the code snippet:
class Base{
public:
inline std::vector<double> getVec(){returnthis->vec;};
inlineunsigned getVecDimension(){returnthis->vec.size();};
protected:
std::vector<double> vec;
}
class ChildA:Base{
ChildA(std::vector<double> vecinit){vec=vecinit;}
}
class ChildB:Base{
protected:
std::vector<Base*> childlist;
public:
ChildB(std::vector<Base*> listofChildren){
childlist=listofChildren;
for(int i=0;i<this->childlist.size();i++){
//HERE WE GET THE ERROR!!!
//terminate called after throwing an instance of 'std::length_error'
// what(): vector::_M_range_insert
//this->vec.size()=0
this->vec.insert(this->vec.end(), childlist[i][0].getVec().begin(), childlist[i][0].getvec().end());
//this->vec.size()=2940?????
}
}
int main(){
std::vector<double> init1 (4,1); //4 Elements=1
std::vector<double> init2 (4,2); //4 Elements=2
ChildA child1(init1);
ChildA child2 (init2);
std::vector<Base*> childlist (2);
childlist[0]=&child1;
childlist[1]=&child2;
ChildB collector (childlist);
}
Any ideas why the size is changing suddenly to that strange number and whats the problem?
The compilation runs without warnings, but the running crashes.
Also with debugging I can't find the issue.
Thank you very much for helping
returns a temporary copy of vec.
Different calls to getVec results in different copies being made.
So in line vec.insert(this->vec.end(), childlist[i][0].getVec().begin(), childlist[i][0].getvec().end());childlist[i][0].getVec().begin() and childlist[i][0].getVec().end() returns iterators to different vectors, causing undefined behavior.
Thank you very much. You both are right!
Returning a vector iterator for begin and end, or storing the vector in a dummy variable, solves the problem.
Returning the iterator seems to be a bit dirty, but takes half of the time than copying it (even worse for bigger vectors).