Wednesday, July 23, 2014

Conditionally remove elemets from a vector in c++

Conditionally remove elemets from a vector in c++

Here is an example for removing empty strings from a std::vector<std::string>:

void testerase() {
    std::vector<std::string> svec {"", "", "hi", "there", ""};
    svec.erase(std::remove_if(svec.begin(), svec.end(), [](std::string const& s) {return s=="";}));
    for(int i=0; i<svec.size(); i++) {
        std::cout << svec[i] << "\n";
    }
}

std::remove_if gives a range and erase erases that range. Note the use of lambda.

0 comments: