Bitset operation in c++
I am trying to pass bitset parameter to the below function but I am not able to:
error: no matching function for call to search(std::bitset<100000000ul>&, int, unsigned int, unsigned int)
Here is the code:
#include <bitset>
#define ELEMENTS 100000000
#define TRANSITION_POINT 500
using namespace std;
template<unsigned int N>
unsigned int search(bitset<N> &array, int value, unsigned int low, unsigned int high) {
unsigned int middle;
.........
}
int main开发者_JAVA技巧() {
const unsigned int NUMBER_OF_ELEMENTS = ELEMENTS;
bitset<NUMBER_OF_ELEMENTS> b;
unsigned int i = 0;
i = TRANSITION_POINT;
while(i < NUMBER_OF_ELEMENTS) {
b[i] = 1;
i++;
}
pos = search(b, (int)1, (unsigned int)0, (unsigned int)NUMBER_OF_ELEMENTS);
return 1;
}
I tried to debug the code but couldnt find what is the problem. Could some one please help.
Your function template expects its first argument to be of type
std::bitset<(unsigned int)NUMBER_OF_ELEMENTS>
but b
is of type
std::bitset<(std::size_t)NUMBER_OF_ELEMENTS>
This subtle difference means that argument-based type inference will fail to match your template (unless std::size_t
happens to be an alias of unsigned int
).
There are two ways to fix it:
- Change the parameter type of your template to
std::size_t
to match that ofstd::bitset
- Explicitly use the function template:
pos = search<NUMBER_OF_ELEMENTS>(b, 1, 0, NUMBER_OF_ELEMENTS);
The code works fine in my g++
compiler. The only error I get is 'pos' is not declared in this scope
. (Also, I think its redundant to typecast to int
and unsigned int
while calling search()
; that's not needed)
With 32 bit gcc 4.4.3 here are the changes that were needed to make it not segfault:
#define ELEMENTS 10000000
Apparently there's a max size, because 100000000
caused it to segfault on bitset<NUMBER_OF_ELEMENTS> b;
b.set(i,1);
The original b[i] = 1
also caused a segfault.
精彩评论