【问题标题】:Removing element from the standard list从标准列表中删除元素
【发布时间】:2017-05-22 23:21:58
【问题描述】:

假设我有以下课程

class Human
 {
public:
    Human();
    Human(string,int);
    virtual ~Human();
    string getName();

protected:

private:
    string name;
    int staj;
 };

我创建了包含 2 个我推入的元素的列表

  list<Human> mylist;
  Human x ("Mike",13);
  Human y("pavlek",33);

如果有名为“Mike”的元素,我正在尝试删除,我尝试像这样删除它:

   for(list<Human>::iterator it=mylist.begin();it!=mylist.end();++it)
  {


  if(it->getName()=="Mike")
  {
      mylist.remove(it);
      cout<< "removed";
       cout<<it->getName();
  }

}

但是,在将值传递给 remove() 函数时出现错误,我应该传递什么才能从列表中删除此元素?

【问题讨论】:

标签: c++


【解决方案1】:

您只是弄错了eraseremove。根据 C++ 参考,remove 用于remove from the list all elements whose values are equals to the given parameter。另一方面,eraseremoves a single element given its position or a range of elements given the start and end positions

如果您只需要删除包含"Mike" 作为其名称的第一个元素,只需执行以下操作:

for(list<Human>::iterator it=mylist.begin();it!=mylist.end();++it)
{
    if(it->getName() == "Mike")
    {
        mylist.erase(it);
        break;
    }
}

请注意after using erase, your iterator will be invalidated。您可以使用erase 的返回值来规避它,这是下一个有效的迭代器值。如果您的列表可能包含多个名称为 "Mike" 的元素,则此详细信息很重要。

【讨论】:

  • 只是重申(请原谅双关语)此代码不起作用。擦除后迭代器无效
【解决方案2】:

Matheus Portela 的解决方案是旧的 C++98 方法。现在容易多了:

mylist.remove_if( [](Human const& h){return h.getName()=="Mike";} );

这里的条件是[](Human const&amp; h){return h.getName()=="Mike";}。这是一个 lambda 表达式,如果应该删除 Human h,则返回 true。您可以在那里测试任何其他属性或属性组合。 lambda 的{ } 部分是一个真正的函数体;你甚至可以在里面有 for 循环:

其他例子:

mylist.remove_if( [](Human const& h){return h.getName().size() > 4; } );

mylist.remove_if( [](Human const& h) {
     for (char c: h.getName())
         if (c=='i') return true; // remove if name contains an i
     return false; } );

请注意,使用std::any_of 会更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-05
    • 2014-12-19
    • 2013-11-25
    • 2016-05-29
    相关资源
    最近更新 更多