std::deque、引用和“流行”

问题描述

我找到了以下代码 here

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::dequepop_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
  }
}

唯一不同的是,我们在没有 pop 的情况下退出循环之前不 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
  }
}

我们将前面的元素移出到局部变量中。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...