I’m lost: An iterator of a vector of std::string works perfectly unless there is a function call (Z_UB->set() ) before it++. Here’s the code:
std::vector< std::string >::iterator it = g_SPP.scenarios->getVector().begin();
std::cout << "begin of vector: " << *it << std::endl;
Z_UB->set("s1", "scn2", 350);
it++;
std::cout << "second of vector: " << *it << std::endl;
creates the following output
begin of vector: scn1
However, if I move the function call like this:
std::vector< std::string >::iterator it = g_SPP.scenarios->getVector().begin();
std::cout << "begin of vector: " << *it << std::endl;
it++;
std::cout << "second of vector: " << *it << std::endl;
Z_UB->set("s1", "scn2", 350);
The result is the following, which is the expected behaviour:
begin of vector: scn1
second of vector: scn2
Inside the Z_UB->set() function there is nothing left but the call itself:
void Parameter::set( std::string _i, std::string _j, float value) {
//int i = indexSets[0]->backIndex(_i);
//int j = indexSets[1]->backIndex(_j);
//data2D[0][0] = value;
}
So if I call the Z_UB->set() function after I created the iterator, accessing it will crash the program. Is there anything vital that I missed about Iterators?
.getVector() returned a copy of the vector. Comparing an iterator to the end point of the iterator of a completely different object doesn’t make sense. Returning a reference solved the problem.
@Xeo also pointed out a much better explanation: When creating an iterator from a copy like this:
the copy immediately is destroyed thus invalidating the just created iterator. So the iterator shouldn’t have returned the first element in the first place, but I can merely guess that this is hidden deeply in the implementation of the compiler.