c++ - 带有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
解决方案
您可以通过删除它所寻址的对象来使迭代器无效(无论您是否为此目的使用它的值)。如果您在那之后尝试访问它,则行为是未定义的(阅读:任何事情都可能发生,例如相同的it
跳转到下一个元素,或者您的程序崩溃)。您不能将其依赖于任何其他行为。
推荐阅读
- mysql - GROUP_CONCAT() 和 GROUP BY 中的 SUM()
- java - 完美的 url 正则表达式
- swift - “无法在此文件中预览 - 无法启动 [应用程序名称]”
- python - 删除整数和句号之间的空格
- r - R中的For-If循环操作
- php - 从 FTP 数组返回的 PHP 数组排序列表
- php - PHP标签内的PHP标签,有替代方案吗?
- flutter-test - 颤振中的错误:widget_test.dart 无法检测到 MyApp()
- node.js - 向不与我的机器人共享服务器的用户发送消息
- python - 如何理解一维数组和二维数组的 numpy dot 生成的维度变化?