我找到了以下代码 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/