Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a pair of numbers in C++?

Tags:

I'm trying to learn C++ and right now I'm writing a program that needs to output a list of pairs of integers.

What is the best way to handle this? I don't have the boost library available on our linux computers at school, so I don't believe I can use boost::tuple.

Any suggestions?

like image 231
Mithrax Avatar asked Jan 29 '10 20:01

Mithrax


People also ask

How do you store values in pairs?

Pair is used to combine together two values that may be of different data types. Pair provides a way to store two heterogeneous objects as a single unit. It is basically used if we want to store tuples. The pair container is a simple container defined in <utility> header consisting of two data elements or objects.

Can we use pair in C?

std::pair takes advantage of templates, so each concrete instantiation defines a new class std::pair<myT1, myT2> . There's no such thing in C, you may have to declare a different struct each time, or use void *...

How do you create a set of pairs?

Sets of pairs in C++Pair is defined under <utility> header and is used to couple together two pair values. The pair can have values of different or same type. The class has member functions first() and second() to individually access the values in a pair. The order of pair elements is fixed (first, second).

How do you get the second element in pair?

To access the elements of the pair, use variable name followed by dot operator followed by the keyword 'first' or 'second', these are public members of class pair.


1 Answers

Have a look at std::pair<object, object>

EDIT:

It's standard C++ and part of what is known as the STL (Standard Template Library). It's a collection of nice data structures that are generic (i.e. may be used to store any C++ object type). This particular structure is used to store a "tuple" or a pair of numbers together. It's basically an object with members "first" and "second" that refer to the first and second objects (of any type!) that you store in them.

So just declare an array of pair<int, int>, or better yet, use another STL type called the "vector" to make a dynamically-sized list of pair<int, int>: vector<pair<int, int> > myList.

Hey what do you know! A dynamically-sized list of pairs already exists and it's called a map! Using it is as simple as #include <map> and declaring a map<int, int> myMap!!!

EDIT:

Yes, as pointed out, a map well "maps" one object to another, so you cannot have repeated lefthand-side values. If that's fine then a map is what you're looking for, otherwise stick to the vector of pair.... or take a look at multimaps.

std::map, std::multimap

like image 79
Mahmoud Al-Qudsi Avatar answered Nov 08 '22 09:11

Mahmoud Al-Qudsi