1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
{
std::vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7,8, 9 } ;
for( auto iter = vec.begin() ; iter != vec.end() ; )
{
// erase returns a valid iterator to the element immediately after the
// one that was erased, or end() if the last element was erased .
if( *iter % 2 ) iter = vec.erase(iter) ;
else ++iter ; // not erase, increment the iterator
}
for( int v : vec ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
{
std::vector<int> vec { 0, 1, 2, 3, 4, 5, 6, 7,8, 9 } ;
// erase-remove idiom
const auto is_odd = []( int v ) { return v%2 == 1 ; } ;
vec.erase( std::remove_if( vec.begin(), vec.end(), is_odd ), vec.end() ) ;
for( int v : vec ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
}
|