增加迭代器标准映射

Igo*_*gor 0 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;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

gcc吐出错误:不匹配operator +.

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

有更好的解决方案吗?

Ker*_* SB 8

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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