I have two classes, the first that contains a vector and a get-method like this:
std::vector<mytype> const& MyClassA::getvector(std::vector<mytype>::iterator &it)
{
it = this->myiterator;
return this->myvector;
}
std::vector<mytype> myvector;
std::vector<mytype>::iterator myiterator;
and I have another class where I should use the vector:
MyClassB::myfunction()
{
std::vector<mytype>::iterator it;
std::vector<mytype> vector = MyClassA->getvector(it);
if (it > vector.begin())
{
....
开发者_JAVA技巧 (--it)->dosomestuff();
....
}
}
in the if I get a runtime exception: iterators incompatible. Why?
EDIT 1
void MyClassA::setvector(mytype myelement)
{
this->myvector.push_back(myelement);
this->myiterator = this->myvector.end() - 1;
}
You have made a copy of the vector in the calling code, and the iterator isn't valid because it's still pointing to the original vector.
You probably intended something like this:
const std::vector<mytype> & vector = MyClassA->getvector(it);
Since you return std::vector<mytype> _const_&
, the type of its iterator is std::vector::const_iterator
.
EDIT:
Ah yes, I'm wrong and Mark Ransom is right. I leave this answer here because of the discussion in the comments, which itself may be useful to someone else.
精彩评论