C++ map容器-59-map容器排序和仿函数

这篇结束学习map容器的API,通过学习map容器的排序,引出一个新的知识点:仿函数,然后继续学习仿函数相关的知识点。

 

1.map容器默认排序

我们知道map容器是该容器本身提供的sort()排序算法,不是直接调用全局静态函数sort(map)去排序。在map容器中默认排序规则是:根据key的ASCII码表进行排序,下面我们用代码来看看。

#include 
#include 
#include 
using namespace std;

void printMap(map& m)
{
    for(map ::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "Key= " << it->first << " ,Value= " << it->second << endl;
    }
}

void test01()
{
    // map容器的构造
    map m;

    // map容器默认排序
    m.insert(pair("Tom", 18));
    m.insert(pair("Anthony", 23));
    m.insert(pair("Bob", 24));
    m.insert(pair("Sunny", 19));
    printMap(m);
    
}

int main()
{
    test01();
    system("pause");
    return 0;
}

这个我们故意插入的key不是按照字母顺序来,打印遍历结果看看是什么规律

运行结果

C++ map容器-59-map容器排序和仿函数_第1张图片

可以看到这个map容器默认是根据key的ASCII码表进行排序的。

 

2.仿函数

有时候我们需要自定义排序,这个时候我们需要用到仿函数。利用仿函数可以改变排序规则,例如我们需要按照key的首字母的降序排序。

#include 
#include 
#include 
using namespace std;

//仿函数
class MyCompare
{

public:
    bool operator()(string s1, string s2)
    {
        return s1 > s2;
    }

};

void printMap(map& m)
{
    for(map ::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "Key= " << it->first << " ,Value= " << it->second << endl;
    }
}

void test01()
{
    // map容器的构造
    map m;

    // map容器默认排序
    m.insert(make_pair("Tom", 18));
    m.insert(make_pair("Anthony", 23));
    m.insert(make_pair("Bob", 24));
    m.insert(make_pair("Sunny", 19));
    printMap(m);
    
}

int main()
{
    test01();
    system("pause");
    return 0;
}

上面代码中的MyCompare 作为一个参数在map的构造中和遍历函数中,这样传入这个仿函数(MyCompare类下的operator()())就可以实现降序输出。

C++ map容器-59-map容器排序和仿函数_第2张图片

仿函数的格式是重载符号()

 

3.函数对象的概念

概念:
重载函数调用操作符的类,其对象常称为函数对象。例如上面代码中的MyCompare类
函数对象使用重载的()时,行为类似函数调用,也叫仿函数

本质:
函数对象(仿函数)是一个类,不是一个函数

特点:

  • 函数对象在使用时,可以像普通函数那样调用,可以有参数,可以有返回值
  • 函数对象超出普通函数的概念,函数对象可以有自己的状态
  • 函数对象可以作为参数传递

你可能感兴趣的:(C++学习笔记)