STL之Map遍历

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

完整code:

 #include
#include
#include
#include
#include
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;
 } 

STL之Map遍历_第1张图片

你可能感兴趣的:(C++,STL)