> m2{ {"张三",10},{"李四",20} };//从小到大排序map > m3{ {"张三",10},{"李四",20} };//定义遍历指针itmap
当前位置:   article > 正文

STL之Map遍历_stl遍历map

stl遍历map
//默认顺序(从小到大)
map<string, int > m1{ {"张三",10},{"李四",20} };
//从大到小排序
map<string, int, greater<string> > m2{ {"张三",10},{"李四",20} };
//从小到大排序
map<string, int, less<string> > m3{ {"张三",10},{"李四",20} };
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
//定义遍历指针it
map<string,int>::iterator it;
for(it=m1.begin();it!=m1.end();it++)
{
	cout<<(*it).first<<" "<<(*it).second<<endl;
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
cout<<"简单遍历方法"<<endl;
for(auto &it:m1)
{
	cout<<it.first<<" "<<it.second<<endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5

完整code:

 #include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const ll N=1e6;
map<string, int > m1{ {"张三",10},{"李四",20} };
map<string, int, greater<string> > m2{ {"张三",10},{"李四",20} };
map<string, int, less<string> > m3{ {"张三",10},{"李四",20} };
int main()
{
	map<string,int>::iterator it;
	cout<<"默认顺序"<<endl; 
	for(it=m1.begin();it!=m1.end();it++)
	{
		cout<<(*it).first<<" "<<(*it).second<<endl;
	} 
	
	cout<<endl;
	cout<<"从大到小"<<endl;
	for(it=m2.begin();it!=m2.end();it++)
	{
		cout<<(*it).first<<" "<<(*it).second<<endl;
	} 
	
	cout<<endl;
	cout<<"从小到大(就是默认顺序)"<<endl;
	for(it=m3.begin();it!=m3.end();it++)
	{
		cout<<(*it).first<<" "<<(*it).second<<endl;
	}  
	
	cout<<endl;
	cout<<"简单遍历方法"<<endl;
	for(auto &it:m1)
	{
		cout<<it.first<<" "<<it.second<<endl;
	}
	return 0;
 } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

SLT之Map遍历

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/450186
推荐阅读
相关标签