algorithm - 从字符串向量中删除_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;
}
解决方案
问题是表达式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()
并且实际上从向量中删除它们。
推荐阅读
- python - r 基于来自 2 个数据帧的列的平方
- list - 使用地图运算符kotlin将对象列表转换为另一个对象?
- python - PyQt5 在浏览器页面上添加文本
- file-permissions - 保存后防止文件修改
- python - livewires MacOS中“初学者”的模块错误 - 初学者
- javascript - 如何在jsPDF的正文中传递具有多个值的数组?
- html - 为什么在将 min-height 设置为父级后,我的具有设置高度的 Flexbox 元素不再起作用?
- excel - 如何使用arrayformula“textjoin”(包括忽略空单元格)?
- ngx-translate - 如何在应用程序中编写的静态类或独立自定义函数中使用 NGX Translate?
- c++ - 需要不同的 LED 以在 arduino 上的电位器的不同级别打开