Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to best access elements of std::pair?

Tags:

c++

std-pair

While using std::pair I came across two different approaches to access its elements. As they both seem to be valid and working I was wondering what is the difference between them and which approach is the preferred one?

std::pair<int, int> p(1,1); // can be of any type.
int i1 = p.first;        // first approach
int i2 = std::get<0>(p); // second approach
like image 969
NewTech Avatar asked Feb 23 '18 10:02

NewTech


1 Answers

If, in a given application, either of pair or 0 is not a literal but a parameter, use get:

template<class... T> auto sum0(const T&... t) {
  return (std::get<0>(t)+...);
}

template<int i> auto sqrAt(const std::pair<int,double> &p) {
  const auto v=std::get<i>(p);
  return v*v;
}

If both pair and 0 are present literally, using .first is plainly preferable for readability reasons (including that it indicates the conscious use of std::pair):

template<class M>
void addKeys(M &m) {
  for(auto &kv : m) kv.second+=kv.first;
}

Everything about this function indicates intended use with std::map or std::unordered_map, making it very readable despite the only type named being void.

like image 101
Davis Herring Avatar answered Sep 20 '22 01:09

Davis Herring