Search code examples
c++arraysstd-pair

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.


Solution

  • 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!