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 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T, typename A > // note: type A is the allocator for the vector
void Erase_Vector_Items( std::vector<T,A>& vec, const T& value ) {
// auto: http://www.stroustrup.com/C++11FAQ.html#auto
for( auto iter = vec.begin() ; iter != vec.end() ; ) {
if( *iter == value ) { // erase this item
// erase returns an iterator to the item immediately after
// the item that was removed (or end if there are no more items)
// update our iterator to refer to the next item
// note: we need to use a construct like this because erase
// "Invalidates iterators and references at or after the point
// of the erase, including the end() iterator."
// https://en.cppreference.com/w/cpp/container/vector/erase
iter = vec.erase(iter) ;
}
else // do not erase this item
++iter ; // / update our iterator to refer to the next item
}
}
// or idiomatic: use the erase-remove idiom
// https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom
template <typename T, typename A > // note: A is the allocator for the vector
void Erase_Vector_Items_2( std::vector<T,A>& vec, const T& value ) {
// https://en.cppreference.com/w/cpp/algorithm/remove
vec.erase( std::remove( vec.begin(), vec.end(), value ), vec.end() ) ;
}
// Write a separate function that will output the contents of the vector (of ANY data-type).////
template <typename T, typename A > // note: A is the allocator for the vector
void Print_Vector_Items( const std::vector<T,A>& vec ) {
// range based loop: http://www.stroustrup.com/C++11FAQ.html#for
for( const auto& v : vec ) std::cout << v << ' ' ;
std::cout << '\n' ;
}
int main() {
// initialiser list: http://www.stroustrup.com/C++11FAQ.html#init-list
std::vector<int> vec { 5, 4, 3, 5, 4, 7, 6, 9, 5, 4, 4, 4, 5 } ;
Print_Vector_Items(vec) ;
Erase_Vector_Items( vec, 5 ) ;
Print_Vector_Items(vec) ;
Erase_Vector_Items_2( vec, 4 ) ;
Print_Vector_Items(vec) ;
}
|