Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 346
Morwenn Avatar asked Oct 19 '25 05:10

Morwenn


2 Answers

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

like image 115
user541686 Avatar answered Oct 21 '25 19:10

user541686


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

like image 37
RedX Avatar answered Oct 21 '25 19:10

RedX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!