Reputation: 892
I am trying to decide whether i should be using an array or a vector for my case which i will describe below:
Consider this scenario: You need to store 3 different types of elements: an integer (this is an integer from 1-4 which represents an output), a boolean (this represents whether the output is true or false), and a second integer (range 0-3 which represents the state). The maximum number of any of these values that can be created is 72.
The way i have achieved this is by creating 3 separate arrays that get filled when an object, containing the above information, is created. Likewise, the object specific information is delete when the object is destroyed. This information is needed from the start of when the application is executed until the application is closed (assuming the object is not destroyed).
Since it is rare to have 72 of these objects created in my application (the use case is highly unlikely), im not sure whether it is smart (as far as the memory is concerned) to initialize these global arrays to 72 from the start, or use a vector and have it grow as the objects are created.
So, my question is, given the above scenario, is it better to use arrays or vectors in that scenario?
Note: One thing to keep in mind is that the index of my arrays represent the specific order of which the objects were created in, making it an easy way to keep track of my elements. I.e., the information at index 0 of any of the three arrays is the information for object 1, etc... Would i be able to keep this same indexing system for reference with the vectors?
Upvotes: 0
Views: 78
Reputation: 48615
I would use std::vector because they will track how many items you have contained in them. I would also pre-allocate enough for all 72
items using the reserve()
method to prevent allocation more than once.
Also I would make a struct
with your 3
values and have one vector of those structs.
struct item
{
int output; // could use std::int8_t to reduce memory
bool valid;
int state; // same here
// (or even use bitfields for all 3 values)
};
// ...
int main()
{
std::vector<item> items;
items.reserve(72); // preallocate enough for all items if you like
// ... etc...
};
If you are really worried about memory you can use bitfields to cram your struct into a single byte:
struct item
{
unsigned char output: 2; // 0-3 (need to add 1 to get 1-4)
unsigned char valid: 1;
unsigned char state: 2; // 0-3
};
Upvotes: 6
Reputation: 1717
Both options are valid. The only thing with arrays is that you need to track how far the array is filled with valid entries, wherein you can ask the vector for its size.
Upvotes: 0