C++ 迭代器的next和prev

C++ 迭代器的next和prev

迭代器的下一个或上一个分别用next和prev获取

#include <string> 
#include <iostream>
#include <iterator>
#include <map>
using namespace std;

int main() {
  map<int, string> map1 = {{ 9,"a1" }, { 7, "a2" }, { 8,"a3" }};
  for (auto it = map1.begin(); it != map1.end(); it++)
  {
    // if (it == map1.end() - 1) cout << map1[it->first] << endl; // map1.end() - 1 编译不通,用一句代替
    if (next(it) == map1.end()) cout << map1[it->first] << endl; // 最后一个元素
    else cout << map1[it->first] << "\t"; // 中间元素
    // if (prev(it) == map1.begin()) cout << "第二个元素" << map1[it->first] << endl; // a3
  } // a2 a3 a1 (按照key由小到大排列)
}

参考:

C++ 参考手册 https://zh.cppreference.com/w/cpp/string/basic_string

猜你喜欢

转载自blog.csdn.net/weixin_42993054/article/details/81951104
今日推荐