Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a vector sort invalidate iterators?

Tags:

c++

sorting

stl

 std::vector<string> names;
 std::vector<string>::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?
like image 561
Ramadheer Singh Avatar asked Oct 07 '10 20:10

Ramadheer Singh


2 Answers

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.

like image 52
Kirill V. Lyadvinsky Avatar answered Oct 11 '22 09:10

Kirill V. Lyadvinsky


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.

like image 16
Jerry Coffin Avatar answered Oct 11 '22 09:10

Jerry Coffin