C++中map的遍历

女爷i 2021-09-19 06:02 1106阅读 0赞

一 点睛

map数据的遍历,也有3种方法

  • 应用前向迭代器方式
  • 应用后向迭代器方式
  • 应用数组方式

二 map反向迭代器的使用实战

1 代码

  1. #include <map>
  2. #include <string>
  3. #include <iostream>
  4. using namespace std;
  5. int main(){
  6. map<int,string> mapStudent;
  7. mapStudent[1] = "student_one";
  8. mapStudent[2] = "student_two";
  9. mapStudent[3] = "student_three";
  10. map<int, string>::reverse_iterator iter;
  11. for(iter = mapStudent.rbegin(); iter != mapStudent.rend(); iter++){
  12. cout<<iter->first<<" "<<iter->second<<endl;
  13. }
  14. return 0;
  15. }

2 运行

  1. [root@localhost charpter03]# g++ 0323.cpp -o 0323
  2. [root@localhost charpter03]# ./0323
  3. 3 student_three
  4. 2 student_two
  5. 1 student_one

3 说明

iter是一个反向迭代器reverse_iterator,它需要rbegin()和rend()方法指出反向遍历的起始位置和终止位置。注意,前向遍历一般是从begin()到end()遍历,而反向遍历则是从ebegin()到rend()

三 用数组方式遍历map

1 代码

  1. #include<map>
  2. #include<string>
  3. #include<iostream>
  4. using namespace std;
  5. int main(){
  6. map<int,string> mapStudent;
  7. mapStudent[1] = "student_one";
  8. mapStudent[2] = "student_two";
  9. mapStudent[3] = "student_three";
  10. int iSize = mapStudent.size();
  11. for(int i = 1; i <= iSize; i++){
  12. cout<<i<<" "<<mapStudent[i]<<endl;
  13. }
  14. return 0;
  15. }

2 运行

  1. [root@localhost charpter03]# g++ 0324.cpp -o 0324
  2. [root@localhost charpter03]# ./0324
  3. 1 student_one
  4. 2 student_two
  5. 3 student_three

3 说明

用size()方法确定当前map中有多少元素。用数字访问vector时,下标是从0-(size-1),而用数字访问map,却是从1~size,这是有所不同的。

发表评论

表情:
评论列表 (有 0 条评论,1106人围观)

还没有评论,来说两句吧...

相关阅读

    相关 c++ vector , set , map

    vector ,set ,和map 属于c++ 的三种容器;遍历三种容器的重要方式是创建iterator ,迭代器在这里扮演了类似指针的角色,用迭代器来指向要访问的索引的值。

    相关 C++map

    一 点睛 map数据的遍历,也有3种方法 应用前向迭代器方式 应用后向迭代器方式 应用数组方式 二 map反向迭代器的使用实战 1 代码 i