温馨提示×

C++ map iterator如何实现自定义排序

c++
小樊
84
2024-07-30 11:23:07
栏目: 编程语言

要实现自定义排序,需要使用std::map的构造函数来传入自定义的比较函数。比如,如果要按照值的大小来排序map,可以定义一个比较函数,然后将其传入std::map的构造函数中。

以下是一个示例代码:

#include <iostream>
#include <map>

// 自定义比较函数
struct Compare {
    bool operator() (const int& a, const int& b) const {
        return a > b;
    }
};

int main() {
    // 使用自定义比较函数进行排序
    std::map<int, std::string, Compare> customMap;

    customMap.insert(std::make_pair(3, "three"));
    customMap.insert(std::make_pair(1, "one"));
    customMap.insert(std::make_pair(2, "two"));

    // 遍历map
    for (auto it = customMap.begin(); it != customMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}

在上面的代码中,我们定义了一个Compare结构体来实现自定义的比较函数,然后将其传入std::map的构造函数中。这样,我们就可以按照值的大小来排序map。

0