如何在std :: map声明上声明自定义排序函数? [英] how to declare custom sort function on std::map declaration?
问题描述
std :: map总是根据值排序键。是否可以按照声明时设置的位数排序?
std::map always sorts keys based on value. Is it possible to make it sort for example on number of bits set upon declaration ?
我有计数设置位的功能:
I have function for counting set bits:
for(size_t i = 0; i < CHAR_BIT * sizeof value; ++i, value >>= 1) {
if ((value & 1) == byteState) ++num_bits;
}
但我不知道如何在声明地图时应用它。 p>
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 declaration <int,int,decltype(countSetBits)>
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},
...
};
这里是 demo on ideone 。它正确地排序128之前的3,因为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屋!