std :: list iterator using - > (箭头)和。 (点)产生不同的结果

时间:2012-02-18 02:01:20

标签: c++

我有以下代码段:

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索引和列表作为值的映射,即std:map<int, std::list<reply_t> >

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

我是c ++的新手,这对我来说完全是奇怪的。任何有可能解释的人?

1 个答案:

答案 0 :(得分:6)

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

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

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