问题描述
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
}
}
唯一不同的是,我们在没有 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
}
}
我们将前面的元素移出到局部变量中。