STL map 按key值和按value值排序

map是用来存放<key, value>键值对的数据结构,能够非常方便高速的依据key查到对应的value。

假如存储水果和其单位价格。我们用map来进行存储就是个不错的选择。

我们这样定义。map<string, double>。当中水果用string类型。作为Key;该水果的单位价格用double类型,作为value。

这样一来,我们能够依据水果名高速的查找到价格。

        我们不仅要将水果和相应的价格输出,还想知道依照价格高低进行排序的结果。

换句话说,我们希望可以对map进行按Key排序或按Value排序。然后按序输出其键值对的内容。

一、C++ STL中Map的按Key排序

 事实上,为了实现高速查找,map内部本身就是按序存储的(比方红黑树)。

在我们插入<key, value>键值对时,就会依照key的大小顺序进行存储。这也是作为key的类型必须可以进行<运算比較的原因。

如今我们用string类型作为key,因此,我们的存储就是按水果名的字典排序储存的。


參考代码:
<pre name="code" class="cpp">#include<iostream>
#include<utility>//<utility>中定义了模板函数make_pair
#include<string>
#include<map>
#include<iterator>
using namespace std;
void  main()
{
	pair<string,double> fruit1("orange",4.5);//初始化
	pair<string,double> fruit2;
	pair<string,double> fruit3;

	//结构体初始化
	fruit2.first="banana";
	fruit2.second=3.25;
    
	//使用模板函数给pair结构体赋值
	fruit3=make_pair("apple",5.2);
	cout<<"pair:"<<endl;
	cout<<"The price of "<<fruit1.first<<" is $"<<fruit1.second<<endl;
	cout<<"The price of "<<fruit2.first<<" is $"<<fruit2.second<<endl;
	cout<<"The price of "<<fruit3.first<<" is $"<<fruit3.second<<endl;

	cout<<endl<<"map:sorted by key(less)"<<endl;
	map<string,double> mapA;
	mapA.insert(fruit1);
	mapA.insert(fruit2);
	mapA.insert(fruit3);
	for(map<string,double>::iterator iter=mapA.begin();iter!=mapA.end();iter++)
	{
		cout<<"The price of "<<iter->first<<" is $"<<iter->second<<endl;
	}
}


执行结果:
pair输出是依照正常生成pair的顺序,map迭代器输出就是经过排序之后的,默认的是key依照字典排序升序排序。
假设要依照key降序排列呢?
map是stl里面的一个模板类,如今我们来看下map的定义:
template < class Key, class T, class Compare = less<Key>,  
           class Allocator = allocator<pair<const Key,T> > > class map;
它有四个參数,当中我们比較熟悉的有两个: Key 和 Value。

第四个是 Allocator,用来定义存储分配模型的,此处我们不作介绍。

如今我们重点看下第三个參数: class Compare = less<Key> 

这也是一个class类型的,并且提供了默认值 less<Key>。 less是stl里面的一个函数对象,那么什么是函数对象呢?

所谓的函数对象:即调用操作符的类,其对象常称为函数对象(function object)。它们是行为类似函数的对象。

表现出一个函数的特征。就是通过“对象名+(參数列表)”的方式使用一个 类,事实上质是对operator()操作符的重载。也就是控制map按key值排序的升降序的。

如今我们来看一下less的实现:


template <class T> struct less : binary_function <T,T,bool> { bool operator() (const T& x, const T& y) const {return x<y;} };
它是一个带模板的struct,里面只对()运算符进行了重载,实现非常easy。但用起来非常方便,这就是函数对象的长处所在。

stl中还为四则运算等常见运算定义了这种函数对象,与less相对的还有greater:

template <class T> struct greater : binary_function <T,T,bool> {  
  bool operator() (const T& x, const T& y) const  
    {return x>y;}  
};  
map这里指定less作为其默认比較函数(对象),所以我们通常假设不自己指定Compare,map中键值对就会依照Key的less顺序进行组织存储,因此我们就看到了上面代码输出结果是依照学生姓名的字典顺序输出的,即string的less序列。

我们能够在定义map的时候,指定它的第三个參数Compare,比方我们把默认的less指定为greater:

map<string,double,greater<string>> mapB;
	mapB.insert(fruit1);
	mapB.insert(fruit2);
	mapB.insert(fruit3);
	cout<<endl<<"map:sorted by key(greater)"<<endl;
	for(map<string,double,greater<string>>::iterator iter1=mapB.begin();iter1!=mapB.end();iter1++)
	{
		cout<<"The price of "<<iter1->first<<" is $"<<iter1->second<<endl;
	}
输出结果为:

降序排列。

如今知道怎样为map指定Compare类了,假设我们想自己写一个compare的类,让map依照我们想要的顺序来存储,比方,依照水果名的长短排序进行存储。那该怎么做呢?

事实上非常easy,仅仅要我们自己写一个函数对象,实现想要的逻辑,定义map的时候把Compare指定为我们自己编写的这个就ok啦。




二、C++ STL中Map的按Value排序


在第一部分中,我们借助map提供的參数接口。为它指定对应Compare类,就能够实现对map按Key排序,是在创建map并不断的向当中加入元素的过程中就会完毕排序。

如今我们想要从map中得到水果价格的从低到高的次序输出,该怎样实现呢?换句话说。该怎样实现Map的按Value排序呢?

        第一反应是利用stl中提供的sort算法实现,这个想法是好的,不幸的是,sort算法有个限制,利用sort算法仅仅能对序列容器进行排序。就是线性的(如vector,list,deque)。

map也是一个集合容器,它里面存储的元素是pair,可是它不是线性存储的(前面提过。像红黑树),所以利用sort不能直接和map结合进行排序。

       尽管不能直接用sort对map进行排序,那么我们可不能够迂回一下,把map中的元素放到序列容器(如vector)中。然后再对这些元素进行排序呢?这个想法看似是可行的。要对序列容器中的元素进行排序,也有个必要条件:就是容器中的元素必须是可比較的,也就是实现了<操作的。

那么我们如今就来看下map中的元素满足这个条件么?

       我们知道map中的元素类型为pair。详细定义例如以下:

template <class T1, class T2> struct pair  
{  
  typedef T1 first_type;  
  typedef T2 second_type;  
  
  T1 first;  
  T2 second;  
  pair() : first(T1()), second(T2()) {}  
  pair(const T1& x, const T2& y) : first(x), second(y) {}  
  template <class U, class V>  
    pair (const pair<U,V> &p) : first(p.first), second(p.second) { }  
}  
pair也是一个模板类,这样就实现了良好的通用性。

它仅有两个数据成员first 和 second,即 key 和 value。并且

<utility>头文件里,还为pair重载了 < 运算符, 详细实现例如以下: 

template<class _T1, class _T2>  
  inline bool  
  operator<(const pair<_T1, _T2>& __x, const pair<_T1, _T2>& __y)  
  { return __x.first < __y.first  
           || (!(__y.first < __x.first) && __x.second < __y.second); }  


重点看下事实上现:
__x.first < __y.first || (!(__y.first < __x.first) && __x.second < __y.second)  


这个less在两种情况下返回true,第一种情况:__x.first < __y.first  这个好理解,就是比較key,假设__x的key 小于 __y的key 则返回true。

另外一种情况有点费解:  !(__y.first < __x.first) && __x.second < __y.second

当然因为||运算具有短路作用,即当前面的条件不满足是,才进行另外一种情况的推断 。第一种情况__x.first < __y.first 不成立,即__x.first >= __y.first 成立。在这个条件下,我们来分析下  !(__y.first < __x.first)  && __x.second < __y.second

 !(__y.first < __x.first) 。看清出,这里是y的key不小于x的key ,结合前提条件,__x.first < __y.first 不成立,即x的key不小于y的key 

即:  !(__y.first < __x.first)  &&   !(__x.first < __y.first )   等价于   __x.first == __y.first ,也就是说,另外一种情况是在key相等的情况下,比較两者的value(second)。

这里比較令人费解的地方就是,为什么不直接写 __x.first == __y.first 呢? 这么写看似费解,但事实上也不无道理:前面讲过,作为map的key必须实现<操作符的重载。可是并不保证==符也被重载了,假设key没有提供==,那么 ,__x.first == __y.first 这样写就错了。由此可见,stl中的代码是相当严谨的。值得我们好好研读。

 如今我们知道了pair类重载了<符。可是它并非依照value进行比較的,而是先对key进行比較。key相等时候才对value进行比較。显然不能满足我们按value进行排序的要求。

并且,既然pair已经重载了<符,并且我们不能改动事实上现,又不能在外部反复实现重载<符。

typedef pair<string, int> PAIR;  
bool operator< (const PAIR& lhs, const PAIR& rhs) {  
    return lhs.second < rhs.second;  
}  

假设pair类本身没有重载<符。那么我们依照上面的代码重载<符,是能够实现对pair的按value比較的。

如今这样做不行了。甚至会出错(编译器不同,严格的就报错)。

那么我们怎样实现对pair按value进行比較呢? 第一种:是最原始的方法,写一个比較函数;  另外一种:刚才用到了。写一个函数对象。

这两种方式实现起来都比較简单。

typedef pair<string, int> PAIR;  
  
bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {  
  return lhs.second < rhs.second;  
}  
  
struct CmpByValue {  
  bool operator()(const PAIR& lhs, const PAIR& rhs) {  
    return lhs.second < rhs.second;  
  }  
};  


接下来,我们看下sort算法。是不是也像map一样,能够让我们自己指定元素间怎样进行比較呢?
template <class RandomAccessIterator>  
  void sort ( RandomAccessIterator first, RandomAccessIterator last );  
  
template <class RandomAccessIterator, class Compare>  
  void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp ); 

  1. 我们看到。令人兴奋的是。sort算法和map一样,也能够让我们指定元素间怎样进行比較,即指定Compare。

    须要注意的是,map是在定义时指定的,所以传參的时候直接传入函数对象的类名。就像指定key和value时指定的类型名一样;sort算法是在调用时指定的,须要传入一个对象,当然这个也简单,类名()就会调用构造函数生成对象。

#include<iostream>
#include<utility>//<utility>中定义了模板函数make_pair
#include<string>
#include<map>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;

typedef pair<string, double> PAIR;  
bool cmp_by_value_less(const PAIR& l,const PAIR& r)
{
	return l.second<r.second;
}

bool cmp_by_value_greater(const PAIR& l,const PAIR& r)
{
	return l.second>r.second;
}
struct CmpByKeyLength {  
  bool operator()(const string& k1, const string& k2) {  
    return k1.length() < k2.length();  
  }  
};  
void  main()
{
	pair<string,double> fruit1("orange",4.5);//初始化
	pair<string,double> fruit2;
	pair<string,double> fruit3;

	//结构体初始化
	fruit2.first="bananas";
	fruit2.second=3.25;
    
	//使用模板函数给pair结构体赋值
	fruit3=make_pair("apple",5.2);
	/*cout<<"pair:"<<endl;
	cout<<"The price of "<<fruit1.first<<" is $"<<fruit1.second<<endl;
	cout<<"The price of "<<fruit2.first<<" is $"<<fruit2.second<<endl;
	cout<<"The price of "<<fruit3.first<<" is $"<<fruit3.second<<endl;*/

	cout<<endl<<"map:sorted by key(less)"<<endl;
	map<string,double> mapA;
	mapA.insert(fruit1);
	mapA.insert(fruit2);
	mapA.insert(fruit3);
	for(map<string,double>::iterator iter=mapA.begin();iter!=mapA.end();iter++)
	{
		cout<<"The price of "<<iter->first<<" is $"<<iter->second<<endl;
	}

	vector<PAIR> vec(mapA.begin(),mapA.end());
	sort(vec.begin(),vec.end(),cmp_by_value_less);
	cout<<endl<<"map:sorted by value(less)"<<endl;
	for(int i=0;i<vec.size();i++)
	{
		cout<<"The price of "<<vec[i].first<<" is $"<<vec[i].second<<endl;
	}

	sort(vec.begin(),vec.end(),cmp_by_value_greater);
	cout<<endl<<"map:sorted by value(greater)"<<endl;
	for(int i=0;i<vec.size();i++)
	{
		cout<<"The price of "<<vec[i].first<<" is $"<<vec[i].second<<endl;
	}

}
依照value值执行结果例如以下:

pair定义和map依照key值升降序以及依照value值升降序的完整代码例如以下:
#include<iostream>
#include<utility>//<utility>中定义了模板函数make_pair
#include<string>
#include<map>
#include<iterator>
#include<vector>
#include<algorithm>
using namespace std;

typedef pair<string, double> PAIR;  
bool cmp_by_value_less(const PAIR& l,const PAIR& r)
{
	return l.second<r.second;
}

bool cmp_by_value_greater(const PAIR& l,const PAIR& r)
{
	return l.second>r.second;
}
struct CmpByKeyLength {  
  bool operator()(const string& k1, const string& k2) {  
    return k1.length() < k2.length();  
  }  
};  
void  main()
{
	pair<string,double> fruit1("orange",4.5);//初始化
	pair<string,double> fruit2;
	pair<string,double> fruit3;

	//结构体初始化
	fruit2.first="bananas";
	fruit2.second=3.25;
    
	//使用模板函数给pair结构体赋值
	fruit3=make_pair("apple",5.2);
	cout<<"pair:"<<endl;
	cout<<"The price of "<<fruit1.first<<" is $"<<fruit1.second<<endl;
	cout<<"The price of "<<fruit2.first<<" is $"<<fruit2.second<<endl;
	cout<<"The price of "<<fruit3.first<<" is $"<<fruit3.second<<endl;

	cout<<endl<<"map:sorted by key(less)"<<endl;
	map<string,double> mapA;
	mapA.insert(fruit1);
	mapA.insert(fruit2);
	mapA.insert(fruit3);
	for(map<string,double>::iterator iter=mapA.begin();iter!=mapA.end();iter++)
	{
		cout<<"The price of "<<iter->first<<" is $"<<iter->second<<endl;
	}

	map<string,double,greater<string>> mapB;
	mapB.insert(fruit1);
	mapB.insert(fruit2);
	mapB.insert(fruit3);
	cout<<endl<<"map:sorted by key(greater)"<<endl;
	for(map<string,double,greater<string>>::iterator iter1=mapB.begin();iter1!=mapB.end();iter1++)
	{
		cout<<"The price of "<<iter1->first<<" is $"<<iter1->second<<endl;
	}

	map<string,double, CmpByKeyLength > mapC;
	mapC.insert(fruit1);
	mapC.insert(fruit2);
	mapC.insert(fruit3);
	cout<<endl<<"map:sorted by length"<<endl;
	for(map<string,double, CmpByKeyLength >::iterator iter2=mapC.begin();iter2!=mapC.end();iter2++)
	{
		cout<<"The price of "<<iter2->first<<" is $"<<iter2->second<<endl;
	}

	vector<PAIR> vec(mapA.begin(),mapA.end());
	sort(vec.begin(),vec.end(),cmp_by_value_less);
	cout<<endl<<"map:sorted by value(less)"<<endl;
	for(int i=0;i<vec.size();i++)
	{
		cout<<"The price of "<<vec[i].first<<" is $"<<vec[i].second<<endl;
	}

	sort(vec.begin(),vec.end(),cmp_by_value_greater);
	cout<<endl<<"map:sorted by value(greater)"<<endl;
	for(int i=0;i<vec.size();i++)
	{
		cout<<"The price of "<<vec[i].first<<" is $"<<vec[i].second<<endl;
	}

}



运行结果例如以下:



原文地址:https://www.cnblogs.com/llguanli/p/7305140.html