如果任何字符串包含特定单词,我需要从字符串向量中删除一些元素。
如何为 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/