从字符串向量中删除_if

Ser*_*gio 2 algorithm c++11

如果任何字符串包含某个单词,我需要从字符串向量中删除一些元素.

我怎样才能写出一元谓词remove_if

这是代码示例:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool remove_if_found(string word)
{
   // ???
}

int main()
{
vector<string> data {
                        { "the guitar has six strings" },
                        { "the violin has four strings" },
                        { "the the violin is more difficult to learn" },
                        { "saxophones are a family of instruments" },
                        { "the drum is a set of percussions" },
                        { "the trumpet is a brass" }
};

cout << data.size() << endl;   // output: 6

remove_if(data.begin(), data.end(), remove_if_found("violin"));  // error

cout << data.size() << endl;    // output should be: 4

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Dei*_*Dei 5

问题是表达式remove_if_found("violin")返回一个bool无法传递给的表达式std::remove_if.

最简单的解决方案就是改变remove_if_found:

void remove_if_found(vector<string>& vec, const string& word)
{
    vec.erase(remove_if(vec.begin(), vec.end(), [&word](const string& el) {
        // check if the word is contained within the string
        return el.find(word) != std::string::npos; 
    }), vec.end()); 
}
Run Code Online (Sandbox Code Playgroud)

它接受向量的引用以及要查找的字符串,并正常进行删除.

然后main你就这样称呼它:

remove_if_found(data, "violin");
Run Code Online (Sandbox Code Playgroud)

删除+删除使用的原因remove_if_function很重要.std::remove_if只是将要移除的元素移动到向量的末尾,并将迭代器返回到第一个(重新)移动的元素.另一方面,std::vector::erase需要两个迭代器 - 从std::remove_if迭代器返回的迭代器,vec.end()并实际上从向量中删除它们.