Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL-pair-like triplet class - do I roll my own?

I want to use a triplet class, as similar as possible to std::pair. STL doesn't seem to have one. I don't want to use something too heavy, like Boost. Is there some useful FOSS non-restrictive-license triplet class I could lift from somewhere? Should I roll my own? Should I do something else entirely?

Edit: About std::tuple...

Is there really no benefit to a triplet-specific class? I mean, with tuple, I can't do

template<typename T1, typename T2, typename T3> std::tuple<T1, T2, T3> triple; 

now can I? Won't I have to typedef individual-type-combination triples?

like image 590
einpoklum Avatar asked Dec 20 '13 14:12

einpoklum


People also ask

How do you store triplets in CPP?

Another solution is to use pair class in C++ STL. We make a pair with first element as normal element and second element as another pair, therefore storing 3 elements simultaneously. // element and second element as another pair. // therefore 3 elements simultaneously.

How do you return a triplet in C++?

Create a HashMap or set to store unique pairs. Run another loop from i+1 to end of the array. (loop counter j) If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break.

What is a pair in STL?

A pair in C++ is described as a container that combines two elements of the same or different data types. The header file for pair in C++ is <utility>. There are various pair STL functions, such as make_pair(), tie(), swap(). We can use nested pair, i.e., the first or second element of a pair is itself a pair.

Can we make pair of pair in C++?

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


1 Answers

No, don't roll your own. Instead, take a look at std::tuple - it's a generalization of std::pair. So here's a value-initialized triple of ints:

std::tuple<int, int, int> triple; 

If you want, you can have a type alias for triples only:

template<typename T1, typename T2, typename T3> using triple = std::tuple<T1, T2, T3>; 
like image 175
Joseph Mansfield Avatar answered Sep 25 '22 08:09

Joseph Mansfield