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

Iterator for a map from a particular position in C++

本文关键字:映射 迭代器 位置 定位 C++      更新时间:2023-10-16

我有一个元素映射和一个嵌套循环来迭代它。但我希望迭代器的行为如下:

    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;
            }
        }
    }

基本上,外循环应该在倒数第二个位置开始终止,内循环必须从外循环迭代器所在的位置开始迭代。但这段代码似乎不起作用。(不匹配it+1中的+)未定义。如有任何帮助,我们将不胜感激。(请指出任何重复的链接,因为我找不到地图。)谢谢!

std::map<K,V,C,A>::iterator是一个双向迭代器,这意味着它既不提供operator+也不提供operator-(只有前缀和postifx形式的operator++operator--)。

在c++11中,仍然可以使用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

在c++03中,您可以使用std::advance()按给定的间隔向前/向后移动(不同之处在于它对实际对象进行操作,而不是像std::next那样创建副本):

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

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

这样的事情也应该起作用。

map<int,int>::iterator it = m.begin();
map<int,int>::iterator end = m.end();
map<int,int>::iterator it1;
bool flag=false;
if ( it != end )
{
   --end;
}
for(it; it != end; it++)
{
   it1 = it;
   for(++it1; it1 != m.end(); it1++)
   {
      if((it->first < it1->first)&&(it->second > it1->second))
      {
         flag=true;
         break;
      }
   }
}