c++ - C++ 中特定位置映射的迭代器

标签 c++ map iterator

我有一个元素映射和一个迭代它的嵌套循环。但我希望迭代器表现得像这样:

    map<int,int>::iterator it;
    map<int,int>::iterator it1;
    bool flag=false;

    for(it=m.begin();it!= m.end()-1;it++)
    {
        for(it1 = it+1;it1 != m.end();it1++)
        {
            if((it->first < it1->first)&&(it->second > it1->second))
            {
                flag=true;
                break;
            }
        }
    }

基本上,外循环应该从最后一个位置开始终止,内循环必须从外循环迭代器所在的位置开始迭代。但是这段代码似乎不起作用。(No Match for + in it+1) is not defined 任何帮助将不胜感激。 (请指出任何重复的链接,因为我找不到 map 链接。)谢谢!

最佳答案

std::map<K,V,C,A>::iterator bidirectional iterator , 这意味着它不提供 operator+都不是operator- (只有前缀和后缀形式的 operator++operator--)。

仍然可以使用 std::next() 移动迭代器或 std::prev() :

for (it = m.begin(); it != std::prev(m.end()); ++it)
//                         ~~~~~~~~^ instead of m.end()-1
{
    for (it1 = std::next(it); it1 != m.end(); ++it1)
    //         ~~~~~~~~^ to get the it+1

你可以使用 std::advance() 而不是按给定的时间间隔向前/向后移动(不同之处在于它对实际对象进行操作,而不是创建像 std::next 这样的拷贝):

it1 = it;
for (std::advance(it1, 1); it1 != m.end(); ++it1)
//        ~~~~~~^      ^ number of steps    

这两种方法都提供了递增/递减给定迭代器的最佳方式(基于该迭代器的特征)。

关于c++ - C++ 中特定位置映射的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872817/

相关文章:

iphone - 移动 MKMapView 点到像素坐标

c++ - 是否有 std::lock_guard<std::mutex> lock(m) 的简写?

map - 获取无效操作 : mymap ["title"] (type interface {} does not support indexing) when trying to index a map

c++ - 按引用返回

java - 为什么 Java 的 Map 接口(interface)有一个 containsValue(Object) 方法,但没有 value->keys 查找?

java - Iterator.hasNext() 似乎不会对列表中的最后一项返回 false

bash - 如何在 Bash 中编写 'for' 循环?

java - 为什么我们使用 entrySet() 方法并使用返回的集合来迭代 map ?

c++ - 将 int 数据存储和读取到 char 数组中

c++ - 尝试使用Windows Midi API时出现gcc错误