Using std::pair and std::tuple is considered bad practice because first, second, and std::get<N> don't provide any information about what is stored in that data field.
The simple solution is to use a struct, for example, if we want to store a point, this can be done:
struct Point{
double x;
double y;
};
The names x and y convey what is stored in that variable, in this case, the x- and y-coordinates of said point, respectively.
The problem with using structs arises when we try to use them in associative containers in that a compiler error will be thrown because operator<(=>) is not defined. The simple solution to THAT problem is to use std::pair or std::tuple. However, this creates a code smell. The more complicated solution to that problem is to start defining some functions:
#include <compare>
struct Point{
double x;
double y;
};
bool operator==(const Point &lhs, const Point &rhs){
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
// Uses lexicographical comparison
std::strong_ordering operator<=>(const Point &lhs, const Point &rhs){
if (lhs.x < rhs.x) return std::strong_ordering::less;
if (lhs.x > rhs.x) return std::strong_ordering::greater;
if (lhs.y < rhs.y) return std::strong_ordering::less;
if (lhs.y > rhs.y) return std::strong_ordering::greater;
return std::strong_ordering::equal;
}
This works, but there is an easier way:
#include <utility>
struct InheritedPoint: std::pair<double, double>{
double &x(){return first;}
double &y(){return second;}
};
The best part is that operator== and operator<(=>) are inherited. The only differences between the directly above Point and InheritedPoint are whether element access uses a method and whether you can construct using a braced-init-list (you can construct using InheritedPoint({x, y}) instead).
For 3D points and other structs with 3 or more data fields, you inherit from std::tuple instead:
#include <tuple>
struct Inherited3DPoint: std::tuple<double, double, double>{
double &x(){return std::get<0>(*this);}
double &y(){return std::get<1>(*this);}
double &z(){return std::get<2>(*this);}
};
And lastly, a useful macro:
#define pair_subclass(T0, f0name, T1, f1name) struct: std::pair<T0, T1>{T0 &f0name(){return first;} T1 &f1name(){return second;}}
InheritedPoint can be defined using typedef pair_subclass(double, x, double, y) InheritedPoint;