4

I need to use a bitset of size 400000000. Just like this:

 #include<iostream>

 #include<bitset>

 using namespace std;

 int main(){
 bitset<400000000> coord;}

But my program crashes because the bitset is too large. So how can I dynamically allocate a bitset? I can't use boost library.

Frank
  • 59
  • 1
  • 2
  • You might consider the much-maligned `std::vector`. – Jerry Coffin Dec 12 '14 at 18:29
  • I can't use that because I'm using bitset to create an array of booleans with size 8 times less the normal – Frank Dec 12 '14 at 18:43
  • @JerryCoffin you should never consider `std::vector` (it is not a container). – mookid Dec 12 '14 at 19:03
  • 3
    @mookid: Sorry, but nonsense. You don't always need a container. Bitset isn't a container either, and nothing else that stores Booleans as a single bit can be. In short, the disadvantages of `std::vector` will apply just as much to any alternative he picks. – Jerry Coffin Dec 12 '14 at 22:11

1 Answers1

3

You can allocate the memory in the heap with new. The heap is much larger than the stack. Code below.

 #include<iostream>

 #include<bitset>

 using namespace std;

 int main(){
    bitset<400000000UL>* coord_ptr = new bitset<400000000UL>();
    bitset<400000000UL> coord = *coord_ptr;
    // <~~ do stuff ~~>
    delete coord_ptr;
 }
dhalik
  • 455
  • 3
  • 11
  • 1
    But then my program crashes when I do something like: #include #include using namespace std; int main(){ bitset<400000000> *coord = new bitset<400000000>; coord[8]=1; } – Frank Dec 12 '14 at 19:01
  • Try this instead: bitset<4000000UL>& coord = *(new bitset<4000000UL>()); I am not sure why this is different but when I compile it it runs fine. – dhalik Dec 12 '14 at 19:26
  • 2
    Please don't actually use this code for anything, that there is a giant memoryleak. – Trent Jan 28 '17 at 12:29