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 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
const auto print = [] ( const auto& seq ) // print the elements of a sequence
{ for( const auto& v : seq ) std::cout << v << ' ' ; std::cout << '\n' ; };
{
std::vector<int> seq { 0, 1, 4, 2, 3, 4, 5, 4, 6, 7, 8, 9 } ;
print(seq) ;
// erase all occurrences of 4
for( auto iter = seq.begin() ; iter != seq.end() ; )
{
// erase: returns a valid iterator to the element immediately after
// the element that was removed
if( *iter == 4 ) iter = seq.erase(iter) ;
else ++iter ;
}
print(seq) ;
}
{
std::vector<int> seq { 0, 1, 4, 2, 3, 4, 5, 4, 6, 7, 8, 9 } ;
print(seq) ;
// erase all occurrences of 4
// erase-remove idiom: https://en.wikipedia.org/wiki/Erase-remove_idiom
seq.erase( std::remove( seq.begin(), seq.end(), 4 ), seq.end() ) ;
print(seq) ;
}
{
std::vector<int> seq { 0, 1, 4, 2, 3, 4, 5, 4, 6, 7, 8, 9 } ;
print(seq) ;
// erase all occurrences of 4
// C++20: https://en.cppreference.com/w/cpp/container/vector/erase2
std::erase( seq, 4 ) ;
print(seq) ;
}
}
|