set和map容器 的排序 自定义函数

本文介绍了如何在C++中使用仿函数(functors)为map和set容器定制排序规则。通过实例展示了如何创建一个自定义比较类MyCompare,使得元素按照从大到小的顺序排列。示例代码展示了如何插入元素并遍历逆序的map容器,强调了理解并运用仿函数来改变容器默认排序的重要性。
摘要由CSDN通过智能技术生成

map 容器
利用仿函数可以指定map容器的排序规则
对于自定义数据类型,map必须要指定排序规则,同set容器
map<int,int,compare> m;
m.insert(make_pair(1,2));

// An highlighted block
class MyCompare 
{ public: bool operator()(int v1, int v2) {
 return v1 > v2; } 
};
void test01() {
//默认从小到大排序 
//利用仿函数实现从大到小排序
map<int, int, MyCompare> m;
m.insert(make_pair(1, 10)); 
m.insert(make_pair(2, 20)); 
m.insert(make_pair(3, 30)); 
m.insert(make_pair(4, 40));
 m.insert(make_pair(5, 50));
for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++) {
cout << "key:" << it->first << " value:" << it->second << endl; }
}
int main() {
 test01();
  system("pause"); 
 return 0; 
 }//


set容器排序
set容器默认排序规则为从小到大,掌握如何改变排序规则
```利用仿函数,可以改变排序规则
下面展示一些 `内联代码片`。

// A code block
var foo = ‘bar’;

#include <map> 
class MyCompare { 
public: bool operator()(int v1, int v2) { 
return v1 > v2; } 
};
void test01() {
 //默认从小到大排序 //利用仿函数实现从大到小排序
  map<int, int, MyCompare> m;
   m.insert(make_pair(1, 10)); m.insert(make_pair(2, 20)); m.insert(make_pair(3, 30)); m.insert(make_pair(4, 40)); m.insert(make_pair(5, 50));
    for (map<int, int, MyCompare>::iterator it = m.begin(); it != m.end(); it++) { 
    cout << "key:" << it->first << " value:" << it->second << endl;
     }
     }
     int main() {
      test01(); 
      system("pause");
       return 0; 
      }
```javascript
// An highlighted block
var foo = 'bar';
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值