Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::pair vs Array

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.

like image 791
Hassan Jalil Avatar asked Jul 22 '14 08:07

Hassan Jalil


People also ask

Are vectors faster than pairs?

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.

What is the difference between std :: array and array?

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.

What are the benefits of using the std :: array?

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.

Is std :: pair contiguous?

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.


1 Answers

You have three choices, and the right one depends on what the two int represent.

  1. using mymap = std::map<int, std::array<float, 2>>;
  2. using mymap = std::map<int, std::pair<float, float>>;
  3. 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!

like image 104
rubenvb Avatar answered Nov 03 '22 21:11

rubenvb