如何在不使用auto关键字的情况下迭代map :: crbegin()

时间:2019-10-23 11:06:42

标签: c++11 stl c++17

我制作了一个地图,我想以相反的顺序对其进行迭代。 我知道我可以这样使用 auto 关键字来做到这一点

#include <bits/stdc++.h>
using namespace std;
int main()
{ 
   map <int,int> mp;

   mp.insert(make_pair(3,30));
   mp.insert(make_pair(4,90));
   mp.insert(make_pair(2,130));
   mp.insert(make_pair(1,20));
   mp.insert(make_pair(5,10)); 

   auto it = mp.crbegin();
   while(it!=mp.crend())
   {
    cout<<it->first <<" "<< it->second <<endl;
     it++;
   }  
}

我可以使用什么代替 auto关键字

下面的代码给我编译错误。

#include <bits/stdc++.h>
using namespace std;
int main()
{ 
  map <int,int> mp;
  mp.insert(make_pair(3,30));
  mp.insert(make_pair(4,90));
  mp.insert(make_pair(2,130));
  mp.insert(make_pair(1,20));
  mp.insert(make_pair(5,10)); 

  map<int,int>::iterator it = mp.crbegin();
  while(it!=mp.crend())
  {
    cout<<it->first <<" "<< it->second <<endl;
    it++;
  }  
}

有可能吗?

1 个答案:

答案 0 :(得分:2)

正确的嵌套类型名称为const_reverse_iterator。因此,它将编译:

map<int,int>::const_reverse_iterator it = mp.crbegin();

但是,auto可能引起争议,在这里使用它可能是常识。

相关问题