std::vector<int> ints; // ... fill ints with random values for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); ) { if(*it < 10) { *it = ints.back(); ints.pop_back(); continue; } it++; }
This code does not work because it is pop_back() itnot valid when called . But I do not find any speaker talking about the validity of iterators in std::vector::pop_back().
pop_back()
it
std::vector::pop_back()
Do you have any links to this?
The call pop_back()removes the last element in the vector, and therefore the iterator for this element is invalid. The call pop_back()does not invalidate the iterators for the elements until the last element, only the redistribution will do this. From Josuttis "C ++ Standard Reference Library":
, , . , , .
, :
23.2.4.2 ( 23.1) , (23.1.1).
23.1.1.12. 68 expressiona.pop_back() return typevoid a.erase(- a.end()) , , deque
, a.pop_back a.erase(- a.end()). :
23.2.4.3.3 - ( ) - -
, pop_back, ( ) .
, , , .
( , ++ 0x,
94 . 732 , pop_back ( ) :
{ iterator tmp = a.end(); --tmp; a.erase(tmp); }
23.1.1, 12 , :
( ), - .
end() - , ():
23.2.6.4 ( vector.erase() 4):
: .
, : pop_back() .
SGI STL (http://www.sgi.com/tech/stl/Vector.html):
[5] . , , , . , , , reserve() , , .
, , pop_back , end(). , , , , . , - , ++ , @mikhaild. : ++ , pop_back.
- , , 10. end(). - , .
. Google - : . 5.
.
pop_back() , . ++:
it, , 10. Visual Studio debug STL , , end(), .
( , , STL-), . , , , .
, "it" , 10, . "it" ints.end(), "it ++" ints.end() + 1, "" ints.end(), :).
" " - ++. ++ 03, ++ 0x - : http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf
" " , pop_back() {iterator = end(); --; (); }. [vector.modifiers] : ": ".
, pop_back ( ), - ( ), , , , .
pop_back() it, . , int 10, :
* it = ints.back();// * , . ints.pop_back();// ;//
, , . , . , , .
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); ) { if(*it < 10) it = ints.erase( it ); else ++it; }
std::remove_if .
std::remove_if
struct LessThanTen { bool operator()( int n ) { return n < 10; } }; ints.erase( std::remove_if( ints.begin(), ints.end(), LessThanTen() ), ints.end() );
std::remove_if ( ) , , .
(cplusplus.com):
, .