I am creating a Map with key and value. The values have to have two separate entries.
Now the first two options that come to my mind is
either go with
Map< int,array[2] >
or
Map < int,pair < float,float > >
Which one of these two is better when it comes to memory and execution time. I personally think array would be better since we do not need to perform any search functions. I just plan to access the location using subscript and changing them.
Swapping 2 vectors will just swap the pointer to the data while std::pair or std:array will have to move/copy each element, which would be costly for large objects. So what you see is not that pair is faster than vector but that pair is faster than vector in that use case.
std::array is just a class version of the classic C array. That means its size is fixed at compile time and it will be allocated as a single chunk (e.g. taking space on the stack). The advantage it has is slightly better performance because there is no indirection between the object and the arrayed data.
std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations.
std::pair is a struct, the standard says the compiler determines the layout though the order must be maintained, so in the instance of std::pair<char,char> your compiler may decide to place 3-byte padding after each char for optimal alignment, so no you can't assume contiguous memory layout - end of story.
You have three choices, and the right one depends on what the two int
represent.
using mymap = std::map<int, std::array<float, 2>>;
using mymap = std::map<int, std::pair<float, float>>;
The preferred option for readable code using this construct:
struct somethingmeaningful { float meaningful1; float meaningful2; };
using mymeaningfulmap = std::map<int, somethingmeaninful>;
Note how the final one magically became meaningful ;-)
.
Also, notice how I completely disregarded your question about which is faster. The reason for this is that it doesn't matter. Readable code with meaningful names is always more performant in the long run!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With