从字符串向量中使用remove_if函数移除元素

3

我需要从一个字符串向量中删除包含特定单词的字符串。

我该如何编写 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;
}

除非您擦除标记为删除的值,否则您的向量不会改变大小。 - Retired Ninja
1个回答

6
问题在于表达式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()); 
}

这个函数需要一个向量的引用以及要查找的字符串,并像正常情况下一样进行删除。

然后在main中,您只需按如下方式调用它:

remove_if_found(data, "violin");

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

考虑解释擦除/删除惯用语,否则第二个大小仍将为6。 - Retired Ninja
@RetiredNinja 感谢您的建议,提供了解释。 - DeiDei
@Sergio 如果这个答案确实帮助解决了你的问题,请接受它,这样问题就可以关闭了。 - DeiDei

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接