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

   2024-10-02 3440
核心提示:要实现自定义排序,需要使用std::map的构造函数来传入自定义的比较函数。比如,如果要按照值的大小来排序map,可以定义一个比较

要实现自定义排序,需要使用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。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号