c++ - std::deque、引用和“pop”
问题描述
我在这里找到了以下代码:
template <typename T>
//some code here
std::queue<T> search_queue;
std::unordered_set<T> searched;
while (!search_queue.empty()) {
T& person = search_queue.front(); // 'T& person' is what I'm particularly interested about.
search_queue.pop();
// some code here
if (searched.find(person) == searched.end()) {
// some code here
}
}
由于std::queue充当底层容器的包装器,在我们的例子中,它是std::deque我们发现以下关于std::deque的pop_front:
对已擦除元素的迭代器和引用无效。
因此,T& person一定是一个错误,因为它所引用的元素在引用创建后立即被删除。
是这样吗?
谢谢。
解决方案
T& person = search_queue.front(); // 'T& person' is what I'm particularly interested about.
search_queue.pop();
是的,在 之后search_queue.pop()
,引用T& person
不再有效。
if (searched.find(person) == searched.end()) {
并且这个(可能还有其他代码)成为未定义的行为。\
一个可能的解决方法是
for (;!search_queue.empty(); search_queue.pop()) {
T& person = search_queue.front(); // 'T& person' is what I'm particularly interested about.
if (searched.find(person) == searched.end()) {
// some code here
}
}
只有在没有ingpop
的情况下退出循环之前我们不这样做,并且在我们迭代之前不会弹出。break
search_queue
另一种选择是
while (!search_queue.empty()) {
T person = std::move(search_queue.front());
search_queue.pop();
if (searched.find(person) == searched.end()) {
// some code here
}
}
我们将前面的元素移出到一个局部变量中。
推荐阅读
- android - 如何在 Oreo(API 级别 28)中运行连续的周期性后台工作(以 15 分钟的周期间隔),甚至在打瞌睡模式下运行?
- angular - 在特定路线上隐藏标题 - 角度 6
- docker - Hyperledger Composer - 多主机安装
- typescript - 如何描述确保嵌套对象具有特定属性的类型
- java - Docker compose 与依赖 mysql 拒绝连接
- r - R的foreach包中工人的表现不佳
- algorithm - 为什么 Apple FileVault 使用块加密算法而不是流加密算法?
- sql - 数据库不会使用用户表单获得新值
- database - 如何在视图页面上显示数据
- python - 如何在 Python 中删除字符串的第一部分和最后一部分?