The following code works as expected (the test passes) but I wonder if working with iterators in this way is considered a bad practice in c++ or if it is okay.
Maybe this is specific for std::vector
and other collections behave differently and best practices vary between collections (or even their implementations)?
It certainly is not okay in other languages and most of the time changing a collection will invalidate iterators and throw exceptions.
BOOST_AUTO_TEST_CASE (ReverseIteratorExample) {
std::vector<int> myvector;
for(int i = 0; i < 5; i++)
{
myvector.push_back(i);
}
// is this generally a bad idea to change the vector while iterating?
// is it okay in this specific case?
myvector.reserve(myvector.size() + myvector.size() - 2 );
myvector.insert(myvector.end(), myvector.rbegin() + 1, myvector.rend() -1);
int resultset [8] = { 0,1,2,3,4,3,2,1 };
std::vector<int> resultVector( resultset, resultset + sizeof(resultset)/sizeof(resultset[0]) );
BOOST_CHECK_EQUAL_COLLECTIONS(myvector.begin(), myvector.end(), resultVector.begin(), resultVector.end());
}
Summarized Questions:
- Is this generally a bad idea to change the vector while iterating?
- Is it okay in this specific case?
- Is this specific for
std::vector
and other collections behave differently? - Do best practices vary between collections (or even their implementations)?