从矢量范围内删除特定元素

removing specific element from vector's range

本文关键字:元素 删除 范围内      更新时间:2023-10-16

如果元素的值与字符串"空"匹配,我想删除元素,因此请彻底迭代循环,但它不是那样工作的。

#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());
  1. 使用 remove_if 将所有找到的"empty"放在 vector 的末尾。
  2. 使用返回的iterator擦除它们。