Skip to content

Instantly share code, notes, and snippets.

@t-mat
Last active December 31, 2015 10:29
Show Gist options
  • Save t-mat/7973174 to your computer and use it in GitHub Desktop.
Save t-mat/7973174 to your computer and use it in GitHub Desktop.
C++ : Erase-remove idiom

C++ : Erase-remove idiom

// http://ideone.com/I2nFCT
#include <vector>
#include <iostream>
#include <algorithm>

template<class T>
void printAll(const T& v) {
    for(const auto& e : v) {
        std::cout << e << " ";
    }
    std::cout << "\n";
}

int main() {
    std::vector<int> v { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    printAll(v);

    v.erase(
        std::remove_if(
            std::begin(v), std::end(v)
            , [](const decltype(v)::value_type& e) {
                return (e % 2) == 0;
            }
        ), std::end(v)
    );
    printAll(v);
}

Result

0 1 2 3 4 5 6 7 8 9 
1 3 5 7 9 

See also

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment