Adding std :: vector with its elements using iterators

The following code works as expected (the test passes), but I wonder if working with iterators this way is bad practice in C ++ or if everything is ok.

Maybe this is specific to std::vector , and other collections behave differently, and best practices differ between collections (or even their implementations)?

This, of course, is not entirely good in other languages, and most of the time changing the collection will invalidate the 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()); } 

General questions:

  • Is it generally a bad idea to change a vector during an iteration?
  • In this particular case, is everything all right?
  • Is this specific to std::vector and other collections behavior differently?
  • Are there better methods for different collections (or even their implementation)?
+6
source share
1 answer

This code is not valid. Standard definition of operations on sequence containers (23.2.3 @ 4):

a.insert (p, i, j) - [...] pre: i and j are not iterators in.

Thus, your code invokes undefined behavior because it violates the precondition for the insert operation.

If instead of using insert you wrote a loop myvector.rbegin() + 1 from myvector.rbegin() + 1 to myvector.rend() -1 and called push_back for all values, your code would be right: this is because push_back only cancels vector iterators if redistribution is required , and your reserve call ensures that it is not.

In the general case, although there are some cases where changing the container when iterating over it is fine (for example, the loop described above), you should make sure that your iterators are not invalid in doing so. When this happens, it is specific to each container.

+12
source

Source: https://habr.com/ru/post/943453/


All Articles