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
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
.
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