c++ STL map容器自定義排序規則


 

一、c++內置類型數據(int,float,double....)

#include <bits/stdc++.h>
using namespace std;

// map容器
void test01()
{
    map<int, string> m;
    // map的幾種初始化操作
    m.insert(make_pair(5, "hhh"));
    m.insert(pair<int, string>(3, "lll"));
    m.emplace(4, "ggg");
    m[1] = "abc";

    //默認排序輸出
    for (map<int, string>::iterator it = m.begin(); it != m.end(); ++it)
    {
        cout << "key:" << it->first << " value:" << it->second << endl;
    }
}

int main()
{
    test01();
    return 0;
}
運行結果:

默認通過key值從小到大排序 

自定義排序規則通常是將升序改為降序

 

1.通過c++自定義的模板函數對象改變排序規則

聲明時加入greater<T1>,使用時應加入頭文件<functional>,或者使用萬能頭文件<bits/stdc++.h>

例如上面的程序map改變聲明為

map<int,string,greater<int>>m;

輸出結果變為

 

 2.通過自定義函數對象改變排序規則

定義比較類如下,通過在類中重載operator()實現函數對象的功能

class Compare
{
public:
    bool operator()(int v1, int v2)
    {
        return v1 > v2;
    }
};

重新將聲明改為

map<int,string,Compare>m;

輸出結果如下

 

 

二、自定義數據類型


#include <bits/stdc++.h>
using namespace std;

// map容器
class Student
{
public:
    int age;
    string name;

    Student() {}
    Student(string name, int age)
    {
        this->name = name;
        this->age = age;
    }
};


//年齡從大到小排,姓名從前往后排
class Comp
{
public:
    bool operator()(const Student &s1, const Student &s2)
    {
  if (s1.age == s2.age)
            return s1.name < s2.name;
        return s1.age > s2.age;
    }
};

void test02()
{
    map<Student, string, Comp> m;
    m.insert(make_pair(Student("aaa", 19), "班長"));
    m.insert(make_pair(Student("bbb", 19), "學習委員"));
    m.insert(make_pair(Student("ccc", 20), "團支書"));
    m.insert(make_pair(Student("ddd", 35), "老師"));
    //輸出
    for (auto it = m.begin(); it != m.end(); ++it)
    {
        cout << "姓名:" << it->first.name << " 年齡:" << it->first.age << " 職務:" << it->second << endl;
    }
}

int main()
{
    test02();
    return 0;
}

輸出結果:

 

....待續

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM