如何在std :: map声明中声明自定义排序函数? [英] How can I declare a custom sort function on std::map declaration?

查看:153
本文介绍了如何在std :: map声明中声明自定义排序函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

容器std::map始终根据键的值对键进行排序.例如,可以对声明时设置的位数进行排序吗?

The container std::map always sorts keys based on their value. Is it possible to make it sort, for example, on the number of bits set upon declaration?

我有一个计数设置位的功能:

I have a function for counting set bits:

for(size_t i = 0; i < CHAR_BIT * sizeof value; ++i, value >>= 1) {
  if ((value & 1) == byteState) ++num_bits;
}

但是我不知道在声明地图时如何应用它:

But I do not know how to apply it when declaring the map:

std::map<int, int> myMap = {
  {1,2},
  {3,4},
  //...
}

我尝试将其作为声明<int,int,decltype(countSetBits)>中的第三个参数,但是没有运气.

I've tried to put it as a third parameter in the declaration <int,int,decltype(countSetBits)>, but with no luck.

推荐答案

您需要将函数包装在二进制运算符中,如下所示:

You need to wrap your function in a binary operator, like this:

#include <iostream>
#include <map>
#include <algorithm>

int cntBits(int value) {
    int num_bits=0;
    for(size_t i = 0; i < 32 ; ++i, value >>= 1) {
        if ((value & 1) == 1) ++num_bits;
    }
    return num_bits;
}

struct cntBitsCmp {
    bool operator()(int a, int b) {
        return cntBits(a) < cntBits(b);
    }
};

现在您可以在声明中使用cntBitsCmp:

Now you can use cntBitsCmp in a declaration:

std::map<int,int,cntBitsCmp> myMap= {
    {128,2},
    {3,4},
    ...
};

这是关于ideone的演示.它正确地将3的顺序定为128,因为3设置了两个位,而128仅设置了一个.

Here is a demo on ideone. It correctly orders 128 ahead of 3, because 3 has two bits set, while 128 has only one.

这篇关于如何在std :: map声明中声明自定义排序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆