开发者

Does a vector sort invalidate iterators?

 std::vector<string> names;
 std::vector<strin开发者_StackOverflow社区g>::iterator start = names.begin();
 std::vector<string>::iterator end = names.end();
 sort (start,end);
 //are my start and end valid at this point?
 //or they do not point to front and tail resp?


According to the C++ Standard §23.1/11:

Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.

§25.3 "Sorting and related operations" doesn't specify that iterators will be invalidated, so iterators in the question should stay valid.


They still point to the beginning and end. The values in those slots of the vector have probably changed, but the storage location in which each resides remains the same.


std::sort will not invalidate iterators to a vector. The sort template uses the * operator on the iterators to access and modify the contents of the vector, and modifying a vector element though an iterator to an element already in the vector will not invalidate any iterators.

In summary,

  • your existing iterators will not be invalidated
  • however, the elements they point to may have been modified

In addition to the support for the standard provided by Kirill V. Lyadvinsky (Does a vector sort invalidate iterators?):

  • 25/5 "Algorithms library"

If an algorithm’s Effects section says that a value pointed to by any iterator passed as an argument is modified, then that algorithm has an additional type requirement: The type of that argument shall satisfy the requirements of a mutable iterator (24.1).

  • 24.1/4 "Iterator requirements"

Besides its category, a forward, bidirectional, or random access iterator can also be mutable or constant depending on whether the result of the expression *i behaves as a reference or as a reference to a constant.


std::vector keeps its elements in contiguous memory. std::sort takes arguments (iterators) by value and re-arranges the sequence between them. The net result is your local variables start and end are still pointing to first and one-past-the-last elements of the vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜