永发信息网

如何将map中的元素倒过来输出

答案:2  悬赏:50  手机版
解决时间 2021-01-26 21:00
  • 提问者网友:爱唱彩虹
  • 2021-01-26 08:18
如何将map中的元素倒过来输出
最佳答案
  • 五星知识达人网友:行路难
  • 2021-01-26 09:15
反向迭代器

#include
using namespace std;

int main()
{
map mp;
// map是红黑排序树, 遍历的时候自然就有序了
for (int i = 0; i < 10; ++i)
{
mp[i] = i + 1;
}
// 正向遍历
map::iterator it = mp.begin();
while (it != mp.end())
{
cout << it->first << ' ' << it->second << " , ";
++it;
}
cout << endl;
// 反向遍历
map::reverse_iterator rIt = mp.rbegin();
while (rIt != mp.rend())
{
cout << rIt->first << ' ' << rIt->second << " , ";
++rIt;
}
cout << endl;
}
全部回答
  • 1楼网友:野慌
  • 2021-01-26 09:25
啥意思? 类似这样? #include  #include  #include  using namespace std; int main(int argc, char const *argv[]) {     map mymap;     mymap.insert(make_pair(4, "apple"));     mymap.insert(make_pair(2, "orange"));     mymap.insert(make_pair(1, "banana"));     mymap.insert(make_pair(3, "grapes"));     mymap.insert(make_pair(6, "mango"));     mymap.insert(make_pair(5, "peach"));     map::const_iterator it;      for (it = mymap.begin(); it != mymap.end(); ++it)         cout << it->first << "=" << it->second << endl;      cout << endl; }运行: 1=banana 2=orange 3=grapes 4=apple 5=peach 6=mango
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯