Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass bitsets with different sizes to a function? [closed]

Tags:

c++

std-bitset

I want to pass bitsets to a function. What size should I assign to the bitset parameter bits in the function prototype if the bitsets have different sizes?

For example:

bitset<3> a;
bitset<4> b;

void ABC(bitset<size> bits){
    ...
}

ABC(a);
ABC(b);
like image 235
pcoder Avatar asked May 26 '14 09:05

pcoder


People also ask

How do you pass Bitset as an argument?

You can templatize the function taking bitset as argument. template <size_t bitsetsize> void ABC(bitset<bitsetsize> a) { ... } This templatized function would be generated by compiler only when you use it somewhere in your code.

Can Bitset be parameterized?

bitset set() function in C++ STL Parameter: The function accepts two parameters which are described below: index – this parameter specifies the position at which the bit has to be set. The parameter is an optional one.


2 Answers

You can templatize the function taking bitset as argument.

template <size_t bitsetsize>
void ABC(bitset<bitsetsize> a) {
   ...
}

This templatized function would be generated by compiler only when you use it somewhere in your code. If you use this function for bitsets of different sizes, separate functions would be instantiated for once for each size. So you should take care to avoid code depending on any local state variables (static variables local to function) as the function instances are different.

It is advisable to use a reference or constant reference to avoid object copy.

template <size_t bitsetsize>
void ABC(const bitset<bitsetsize> &a) {
   ...
}

An alternative which may not be fit for your requirements is to use std::vector<bool> instead of std::bitset if possible.

like image 138
Mohit Jain Avatar answered Sep 30 '22 09:09

Mohit Jain


This is not possible with STL bitset.

std::bitset<N> template requires a fixed size in advance (at compile-time)

However, one way you can do this by using boost::dynamic_bitset


Something like following:

#include <iostream>
#include <boost/dynamic_bitset.hpp>

void ABC(boost::dynamic_bitset<> &a)
{
    /* for (boost::dynamic_bitset<>::size_type i = 0;
            i < a.size(); ++i)
          std::cout << a[i]; */
    std::cout << a << "\n";
}


int main()
{
    std::size_t size= 5; // take any value for 'size' at runtime

    boost::dynamic_bitset<> x(size); // all 0's by default
    x[0] = 1;
    x[1] = 1;
    x[4] = 1;
    ABC( x );

    return 0;
}

See here

like image 24
P0W Avatar answered Sep 30 '22 09:09

P0W