【问题标题】:removing specific element from vector's range从向量的范围中删除特定元素
【发布时间】:2014-11-05 10:23:32
【问题描述】:

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

#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"); 

那么如何以较低的复杂性实现它?

【问题讨论】:

标签: c++ vector stl stdvector


【解决方案1】:

你应该像这样使用 std::remove_if:

myvector.erase(std::remove_if(myvector.begin(), myvector.end(), [](const std::string& string){ return (string == "empty"); }), myvector.end());

【讨论】:

  • 这里不需要使用std::remove_if和一个lambda,为什么不简单地使用std::remove"empty"的值?
【解决方案2】:
    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 删除它们。

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多