Search code examples
c++c++11std-pairidiomsstdarray

Idiomatic way to store two related values of the same type


This will be a pretty simple question: in C++03, I would store two values of the same type with std::pair. However, having to repeat the type twice is somehow a bother when I want both of my values to be of the same type. Now, with C++11, we have std::array. Would it be more idiomatic to write this:

std::array<int, 2> foo;

...instead of that:

std::pair<int, int> foo;

...when the aim is to store two related data (picture for example the result of a function solving a quadratic equation)?


Solution

  • I don't think there's any data type suitable for this in either the standard library or in Boost.

    pair<T, T> is definitely wrong:
    make_pair(1, 2) == make_pair(2, 1) should be true if these represent the roots of a polynomial!

    For the same reason, an array/vector won't work either, unless you change the comparison behavior.

    So I'd say make a bag<T, N> data type that represents a multiset<T> with a fixed size, kind of like how array<T, N> represents a vector<T> with a fixed size.

    Since the size is small, you can just do everything by brute force (comparison, equality checking, etc.).