服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 浅析stl序列容器(map和set)的仿函数排序

浅析stl序列容器(map和set)的仿函数排序

2020-12-31 16:01C语言教程网 C/C++

有序的stl容器在工程中应用什么方便和广泛,但是当我们需要自己的排序的时候,可以用仿函数来设置它

问题:set是一个自动有序的集合容器,这是set的一个最实惠的性质,从小到大,只要你插入进去,就有序了。但是,如果你不想要这个顺序呢,是不是可以人为控制set容器
的元素顺序呢?答案是,可以的,因为stl也是程序员设计的。

首先看stl的模板构造函数

复制代码 代码如下:

explicit set ( const Compare& comp = Compare(), const Allocator& = Allocator() );
template
set ( InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator() );
set ( const set& x );


我们完全可以重定义set的构造函数里的比较函数,完成对set的自排序功能。

 

举例:

复制代码 代码如下:


bool fncomp (int lhs, int rhs) {return lhs
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs>rhs;} // 控制set逆序
};

 

void testset()
{
// 第一种使用方法
bool(*fn_pt)(int,int) = fncomp;
set sixth (fn_pt);
// 第二中使用方法
set s;                 // class as Compare
s.insert(4);
s.insert(5);
set::iterator it;
for(it=s.begin();it!=s.end();it++)
{
cout<<*it<<" ";
}
cout <<endl;
};


注意:如果set元素是一个结构体,你最好要设置你的仿函数,不然set一般默认是按第一个字段排序的,而我们的实际情况是想按序号i排序:

复制代码 代码如下:


struct ST_Message
{
public:
ST_Message(int seq, int64_t time, string strfrom, string strto, string strinfo){
this->seq=seq;this->time=time;this->strfrom=strfrom;this->strto=strto;this->strinfo=strinfo;}

 

int seq;
int64_t time;
string strfrom;
string strto;
string strinfo;

bool operator <(const ST_Message& other) const // 注意是const函数
{
if (seq != other.seq) // dtime按升序排序
{
return (seq < other.seq);
}
else if(time < other.time)
{
return (time < other.time);
}
else if(strcmp(strfrom.c_str(), other.strfrom.c_str()) != 0)
{
return (strcmp(strfrom.c_str(), other.strfrom.c_str()) < 0);
}
else if(strcmp(strto.c_str(), other.strto.c_str()) != 0)
{
return (strcmp(strto.c_str(), other.strto.c_str()) < 0);
}
else
{
return (strcmp(strinfo.c_str(), other.strinfo.c_str()) < 0);
}
}
};


stl中自动有序的容器map也和set有相同的应用,如果你想快速理解,那么把这篇文章中的set改成map就差不多了。

总之,有序的stl容器在工程中应用什么方便和广泛,但是当我们需要自己的排序的时候,可以用仿函数来设置它!

延伸 · 阅读

精彩推荐