从矢量范围内删除特定元素
removing specific element from vector's range
如果元素的值与字符串"空"匹配,我想删除元素,因此请彻底迭代循环,但它不是那样工作的。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
std::vector<std::string> myvector;
myvector.push_back("value");
myvector.push_back("value");
myvector.push_back("empty");
myvector.push_back("value");
myvector.push_back("value");
myvector.push_back("empty");
myvector.push_back("empty");
int index = 0;
for(string input: myvector){
if(input == "empty")
myvector.erase(myvector.begin()+index,myvector.begin()+index);
index++;
}
for(string input: myvector){
cout << input << endl;
}
return 0;
}
但是我们可以看到没有删除任何内容?
输出 :
value
value
empty
value
value
empty
empty
寻找类似下面但不存在的东西
myvector.erase(myvector.begin(),myvector.end(),"empty");
那么如何以更低的复杂性实现它呢?
你应该像这样使用 std::remove_if:
myvector.erase(std::remove_if(myvector.begin(), myvector.end(), [](const std::string& string){ return (string == "empty"); }), myvector.end());
std::vector<std::string> myvector;
myvector.push_back("value");
myvector.push_back("value");
myvector.push_back("empty");
myvector.push_back("value");
myvector.push_back("value");
myvector.push_back("empty");
myvector.push_back("empty");
auto it = std::remove_if(myvector.begin(), myvector.end(),
[](const std::string& s)
{
return (s== "empty");
});
myvector.erase(it, myvector.end());
- 使用
remove_if
将所有找到的"empty"
放在vector
的末尾。 - 使用返回的
iterator
擦除它们。
相关文章:
- C++如何通过用户输入删除列表元素
- 使用函数"remove"删除重复元素
- 如何通过 getter 函数删除矢量的元素?
- 从控制台中删除最后打印的元素
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 从矢量中删除元素后出现隔离错误
- 删除映射和分割错误中的一个过去结束元素
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- 从矢量中删除空元素
- 关于比较两个无序数组并删除 a[] 中可以在 b[] 中找到的元素的问题
- 删除指针数组 (C++) 中的元素
- 删除列表 c++ 中的最后 3 个元素
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 从std::multiset的第i个元素删除到末尾
- 删除 [] 是否等于每个元素删除.C++
- std::列出元素删除后节点的内存回收