Avoid adding structure in C ++

In my code, I have the following struct :

 struct foo { int a; int b; }; 

Only values ​​from 0 to 100 are stored in b In general, I could replace it with char . But the size of the struct same due to padding effects. Since my code contains vectors and sets this structure with several million entries, this will reduce memory usage by more than one third if I somehow get around the add-on. Is there any way to do this, for example. Is there any other (optional) data container that behaves in the same way?

Edit: I use both GNU and Intel compiler on Linux systems:

+6
source share
2 answers

Moving my comment as an answer as reported to the community :)

It depends on the compiler. You need to use struct pack ing.

For Visual Studio you need #pragma pack and for gcc , you need to use the packed attribute.

See the issue of aligning the C ++ structure for more information.

Hope this helps, sorry I can't check it now, but what do you need

+6
source

With the exception of using special #pragma to control padding / alignment of the structure, you can separate a and b and save them in a separate vector s and "match" them by index.

As for set s, even if you can easily break down a structure into its constituent parts (which you probably cannot from a purely logical point of view - set have no indexes), you will still pay to align the dynamic memory management, which is probably will erase all the benefits you could get with this.

+2
source

All Articles