Question

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)?

Was it helpful?

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

OTHER TIPS

I'd still use pair to indicate that one value is related to the other. Array does not convey that meaning to me.

std::pair makes sense if you have relation between two items, and you want to describe that relation.

However, in your case I would use std::array, as two solutions of quadratic equation don't have any relationship between each other (I can see the relationship between the solutions and the equatiation, but not between two solutions).

Depends on the larger context.

In the example you mentioned I'd go with std::array, because then you can also template the function on the degree of the equation:

template <int N>
std::array<double, N> solveEquation(const Polynomial<N>& poly);

I'd say the corresponding C++11 abstraction of std::pair<> is std::tuple<>, since a pair is just a special case of tuple.

std::pair<> doesn't hold equal types necessarily, BTW.

Precisely for idiomatic reasons, I would suggest using pair a denotes that both values are related while array is more related to a list of values (in my humble opinion).

For example, in your suggested usage, the relation between both values would be the quadratic function itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top