Search code examples
c++bitset

How can I use bitset in map?


I am trying to store 0 to 25 numbers along with its 5 bit representation using bitset.
Here is the code :

int main()
{
   
   map<int, bitset<5> > myMap;
   myMap[0] = 00000;
   myMap[1] = 00001;
   myMap[2] = 00010;
   myMap[3] = 00011;

   // Like this I have stored 0 to 25 numbers.     
    
   auto pos = myMap.find(2);
   cout<< pos-> second <<endl;  // output is 01000
   
   pos = myMap.find(3);
   cout<< pos->second <<endl;   // output is 01001

   pos = myMap.find(15);
   cout<< pos->second <<endl;   // output is 01001

   pos = myMap.find(12);
   cout<< pos->second <<endl;   // output is 00000
   return 0;
}  

It seems that my output is wrong.
Where I am wrong ?


Solution

  • In this line:

    myMap[2] = 00010;
    

    The int literal is converted to a bitset. The octal literal 00010 is decimal 8, which prints the output 01000. Similarly, the literal 00011 is decimal 9, which prints 01001.

    You seem to want:

    myMap[0] = 0;
    myMap[1] = 1;
    myMap[2] = 2;
    myMap[3] = 3;
    // etc.
    
    // or simply
    for(int i = 0; i < 25; ++i)
      myMap[i] = i;
    

    Here's a demo.