首页 > 解决方案 > 带有while循环的C ++ 11反向迭代器

问题描述

我知道代码不是好的做法,所以问题不在于这个。我只想了解以下示例的工作原理。请注意,当我调用 remove 时,我没有对迭代器做任何事情,所以当循环进入下一次迭代时,它是如何指向下一个元素的?

#include <string>
#include <list>
#include <algorithm>
#include <iostream>

class Obj;
std::list<Obj> objs;

class Obj
{
public:
  Obj(const std::string& name, int age)
  : name_(name), age_(age)
  {}

  std::string name()
  {
    return name_;
  }

  int age()
  {
    return age_;
  }
private:
  std::string name_;
  int age_;
};


void remove(const std::string& name)
{
  auto it = find_if(objs.begin(), objs.end(),[name] (Obj& o) { return (o.name() == name); });
  if (it != objs.end())
  {
    std::cout << "removing " << it->name() << std::endl;
    objs.erase(it);
  }
}

int main()
{
  objs.emplace_back("bob", 31);
  objs.emplace_back("alice", 30);
  objs.emplace_back("kevin", 25);
  objs.emplace_back("tom", 45);
  objs.emplace_back("bart", 37);
  objs.emplace_back("koen", 48);
  objs.emplace_back("jef", 23);
  objs.emplace_back("sara", 22);

  auto it = objs.rbegin();
  while (it != objs.rend())
  {

   std::cout << it->name() << std::endl;

   if (it->name() == "tom")
   {
      remove(it->name()); //notice I don't do anything to change the iterator
   }
   else
   {
     ++it;
   }
  }
  return 0;
}

以下是输出:

sara
jef
koen
bart
tom
removing tom
kevin
alice
bob

标签: c++listc++11iteratorreverse-iterator

解决方案


您可以通过删除它所寻址的对象来使迭代器无效(无论您是否为此目的使用它的值)。如果您在那之后尝试访问它,则行为是未定义的(阅读:任何事情都可能发生,例如相同的it跳转到下一个元素,或者您的程序崩溃)。您不能将其依赖于任何其他行为。


推荐阅读