Home > Blockchain >  Which method is faster to access Pairs?
Which method is faster to access Pairs?

Time:12-15

just to clear this doubt of fine i just want to ask that which method is faster or more efficient to access pairs while iterating over a contiguous block of pairs.

I used two method to iterate over a block.

1st

  pair<int, char> arr[3] = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
   
for (int i = 0; i < 3;i  ){
        cout << get<0>(arr[i]) << " " << get<1>(arr[i]) << endl;
    }    
    

2nd

 for(const auto &x:arr){
    cout << x.first << " " << x.second << endl;
    get<0>(arr[0]);
}

which one is better and more efficient pls explain if u can.

CodePudding user response:

You can compare them here: https://godbolt.org/z/4dPzKaPWr

As you will see, both have the same assembly code.

CodePudding user response:

They are the same. The template arguments 0 and 1 in get<> must be compile-time constants, An implementation of get<>() refers to first or second for 0 or 1 respectively. The function call to get<>() gets inlined when optimized.

CodePudding user response:

Efficiency takes many forms. I don't expect huge runtime differences in either case (you will have to measure/profile and expect std::cout to slow things down a lot, so be careful what you measure!). But in terms of maintainability (which is also an efficiency). I would use structured bindings on pairs (or not use pairs at all and use my own struct with clearly readable names)

#include <iostream>
#include <utility>

// don't use : using namespace std

struct my_data_t
{
    int number;
    char character;
};


int main()
{
    std::pair<int, char> arr[]{{1, 'a'}, {2, 'b'}, {3, 'c'}};
    my_data_t arr2[]{{1, 'a'}, {2, 'b'}, {3, 'c'}};
    
    // using structured bindings for readabiliey
    for(const auto& [number, character] : arr)
    {
       // for speed, don't use std::endl though
       std::cout << number <<", " << character << "\n"; 
    }
    
    // or using own datastructure
    for(const auto& entry : arr2)
    {
        std::cout << entry.number <<", " << entry.character << "\n"; 
    }
    
    return 0;
}
  • Related