全部,
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/