std::list 迭代器 使用 ->(箭头)和 .(点)产生不同的结果

std::list iterator using -> (arrow) and . (dot) produces different results

本文关键字:结果 箭头 使用 迭代器 gt std list      更新时间:2023-10-16

我有以下代码段:

std::list<reply_t> l = m[index];
for (std::list<reply_t>::iterator it = l.begin(); it != l.end(); it++) {
    // do something
}

std::list<reply_t> *l = &(m[index]);
for (std::list<reply_t>::iterator it = l->begin(); it != l->end(); it++) {
    // do something
}

m只是一个以int index和list为值的映射,即std:map<int, std::list<reply_t> >

这两个版本只在引用列表的方式上有所不同(一个按指针,一个按对象)。我代码中的其他所有内容都完全相同。然而,当我使用这两个版本运行时,版本1始终未通过测试,版本2一直成功。如果有帮助的话,代码是在多线程上下文中使用的。

我是c++的新手,这对我来说很奇怪。有人能解释一下吗?

这两个例子的不同之处在于,第一个例子创建了m[index]返回的列表的副本,然后对该副本进行迭代。

要匹配第二个版本,您需要使用列表的引用。试试这个:

std::list<reply_t>& l = m[index]; // notice extra '&' character.