c++ - std::deque、引用和 'pop'

标签 c++ reference queue 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::deque pop_front :

Iterators and references to the erased element are invalidated.


因此, T&人 一定是错误的,因为它引用的元素在创建引用后立即被删除。
是这样吗?
谢谢。

最佳答案

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 的情况下退出循环ing 和 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
  }
}
我们将前面的元素移出到局部变量中。

关于c++ - std::deque、引用和 'pop',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68165367/

相关文章:

c++ - CMake 属性和扩展生成器表达式

c++ - c++11/1y lambda 函数的类型签名是什么?

C: 我怎样才能改变变量写入的寄存器?

java - 将消息存储到变量 RabbitMQ Java

multithreading - Python 多处理队列慢

c++ - Antlr4 C++访问歧义分支

c++ - 在动态加载的库中我的内存分配在哪里?

r - R 中出现 "Variable Lengths Differ"错误的原因是什么?

build - F# 命名空间未定义

python - 如何在 pythonrabbitmq 中检查消息是否在过去 5 秒内未发送