algorithm - 从字符串向量中移除_if

标签 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;
}

最佳答案

问题是表达式 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() 并实际上将它们从矢量中删除。

关于algorithm - 从字符串向量中移除_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50321204/

相关文章:

c - 理解/澄清c代码的逻辑

ruby - 置换的递归解

c++ - 我真的需要为 const 对象实现用户提供的构造函数吗?

c++ - 如何删除二维 vector 中的列,C++

c++ - 将未知大小的 std::array 传递给函数

algorithm - 流数据和识别主题的数据结构/算法

python - 如何从该表构建所有可能元组的列表?

c++ - 为什么按值捕获 std::istringstream 右值的 Op 不符合 Accumulateable 概念?

algorithm - 搜索满足特定条件的所有区间

c++ - 在 vs2015 中使用 std::functional 的误报错误