c++ - 增加迭代器标准映射

标签 c++ dictionary iterator

全部,

std::map<int, std::string> addressee;
std::map<int, std::string>::iterator it1, it2;

for( it1 = addressee.begin(); it1 != addressee().end(); it1++ )
{
    bool found = false;
    for( it2 = it1 + 1; it2 != addressee.end() && !found; it2++ )
    {
       if( it1->second == it1->second )
       {
           printf( "Multiple occurences of addressees found" );
           found = true;
       }
    }
}

gcc 报错:不匹配 operator+。

这段代码是我现在正在尝试做的事情的简化版本。我想我可以使用 std::advance(),但它似乎只会浪费函数调用。

有更好的解决方法吗?

最佳答案

std::map 没有随机访问迭代器,只有双向迭代器,所以没有 + n 操作。相反,使用 std::next :

#include <iterator>
#include <map>

// ...

for (auto it1 = addressee.begin(), e = addressee.end(); it1 != e; ++it1)
{
    for (auto it2 = std::next(it1); it2 != e; ++it2)
    {
        if (it1->second == it2->second)
        {
            // ...
            break;
        }
    }
}

事实上,您应该始终使用std::next,因为它知道其参数属于哪个迭代器类别以及计算下一个迭代器的最有效方法是什么.这样,您就不必关心您碰巧使用的具体容器。

关于c++ - 增加迭代器标准映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820047/

相关文章:

c++ - 为什么 gdb 显示两种不同的返回?

c++ - 将成员函数转换为指向成员函数的指针

r - 如何通过 ID 有效计算 map 中的 difftime

c++ - string::replace 是否会使迭代器和引用失效?

c++ - 如何固定输出 C++、STL 中文本的位置

c++ - 使用 glm 时翻转 Z 坐标

c++ - 如何停止有关未使用的私有(private)字段的警告?

python - 两个字典列表的交集?

python - 在 Django 模板中循环字典的字典只需 1 行代码

c++ - 当 Visual Studio 运行正常时, vector 迭代器上的 LInux g++ 编译器错误