首页 > 解决方案 > 从字符串向量中删除_if

问题描述

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

我怎样才能写一元谓词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;
}

标签: algorithmc++11

解决方案


问题是表达式remove_if_found("violin")返回的 abool不能传递给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()); 
}

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

然后在main你这样称呼它:

remove_if_found(data, "violin");

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


推荐阅读