What is std::pair
for, why would I use it, and what benefits does boost::compressed_pair
bring?
C++ pair is a type that is specified under the utility> header and is used to connect two pair values. The pair's values can be of separate or identical types. To view the values in a pair independently, the class has the member functions first() and second().
Essentially std::pair is still a struct.
A pair is a single unit with two members. A map has keys and values in it. So you can use pairs to fill up a map, the elements of the pair becoming key and value.
compressed_pair
uses some template trickery to save space. In C++, an object (small o) can not have the same address as a different object.
So even if you have
struct A { };
A
's size will not be 0, because then:
A a1; A a2; &a1 == &a2;
would hold, which is not allowed.
But many compilers will do what is called the "empty base class optimization":
struct A { }; struct B { int x; }; struct C : public A { int x; };
Here, it is fine for B
and C
to have the same size, even if sizeof(A)
can't be zero.
So boost::compressed_pair
takes advantage of this optimization and will, where possible, inherit from one or the other of the types in the pair if it is empty.
So a std::pair
might look like (I've elided a good deal, ctors etc.):
template<typename FirstType, typename SecondType> struct pair { FirstType first; SecondType second; };
That means if either FirstType
or SecondType
is A
, your pair<A, int>
has to be bigger than sizeof(int)
.
But if you use compressed_pair
, its generated code will look akin to:
struct compressed_pair<A,int> : private A { int second_; A first() { return *this; } int second() { return second_; } };
And compressed_pair<A,int>
will only be as big as sizeof(int).
std::pair
is a data type for grouping two values together as a single object. std::map
uses it for key, value pairs.
While you're learning pair
, you might check out tuple
. It's like pair
but for grouping an arbitrary number of values. tuple
is part of TR1 and many compilers already include it with their Standard Library implementations.
Also, checkout Chapter 1, "Tuples," of the book The C++ Standard Library Extensions: A Tutorial and Reference by Pete Becker, ISBN-13: 9780321412997, for a thorough explanation.
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