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

Mithrax picture Mithrax · Jan 29, 2010 · Viewed 42k times · Source

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?

Answer

Mahmoud Al-Qudsi picture Mahmoud Al-Qudsi · Jan 29, 2010

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