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 58 59 60 61 62 63 64 65 66 67 68 69 70
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template <typename iter_type>
void print(iter_type beg, iter_type end)
{
std::cout << "{ ";
while (beg != end)
std::cout << *beg++ << ' ';
std::cout << "}\n";
}
template <typename container_type>
void print(const container_type& container)
{
print(std::begin(container), std::end(container));
}
void remove_copies_of_front_with_remove_erase_idiom(std::vector<int>& v)
{
v.erase(std::remove(v.begin()+1, v.end(), v.front()), v.end());
}
void remove_copies_of_front_with_while_loop(std::vector<int>& v)
{
unsigned i = 1;
while (i < v.size())
{
if (v[i] == v[0])
v.erase(v.begin() + i);
else
++i;
}
}
int main()
{
using vec_t = std::vector<int>;
vec_t original = { 1, 1, 1, 2, 1, 3, 1, 1, 4, 1, 1, 5 };
vec_t expected_result = { 1, 2, 3, 4, 5 };
auto a = original;
std::cout << "Before remove-erase idiom applied\n\ta: ";
print(a);
remove_copies_of_front_with_remove_erase_idiom(a);
std::cout << "\nAfter removal\n\ta: ";
print(a);
if (a == expected_result)
std::cout << "Success!\n\n";
else
std::cout << "Failure!\n\n";
auto b = original;
std::cout << "Before while removal\n\tb: ";
print(b);
remove_copies_of_front_with_while_loop(b);
std::cout << "\nAfter removal\n\tb: ";
print(b);
if (b == expected_result)
std::cout << "Success!\n\n";
else
std::cout << "Failure!\n\n";
}
|