#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";
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgojaW5jbHVkZSA8aXRlcmF0b3I+Cgp0ZW1wbGF0ZSA8dHlwZW5hbWUgaXRlcl90eXBlPgp2b2lkIHByaW50KGl0ZXJfdHlwZSBiZWcsIGl0ZXJfdHlwZSBlbmQpCnsKICAgIHN0ZDo6Y291dCA8PCAieyAiOwogICAgd2hpbGUgKGJlZyAhPSBlbmQpCiAgICAgICAgc3RkOjpjb3V0IDw8ICpiZWcrKyA8PCAnICc7CiAgICBzdGQ6OmNvdXQgPDwgIn1cbiI7Cn0KCnRlbXBsYXRlIDx0eXBlbmFt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