增加迭代器标准映射 [英] Increment an iterator standard map

查看:127
本文介绍了增加迭代器标准映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ALL,

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吐出错误:不匹配运算符+。

gcc spits out an error: no match for operator+.

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

This code is a simplified version of what I'm trying to do right now. I guess I can use std::advance(), but it seems it just going to be a waste of the function call.

有更好的解决方法吗?

Is there a better fix for that?

推荐答案

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

std::map does not have random access iterators, only bidirectional iterators, so there's no + n operation. Instead, use 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 ::接下来,因为它知道该迭代器类别的说法有和计算什么是最有效的方式接下来的迭代器。这样,您就不必关心您正在使用的特定容器。

In fact, you should always use std::next, since it knows which iterator category its argument has and what the most efficient way to compute the next iterator is. That way, you don't have to care about the specific container you happen to be using.

这篇关于增加迭代器标准映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆