How can I store a pair of numbers in C++?
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 w开发者_StackOverflow社区ay 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?
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
Use std::pair?
#include <utility>
#include <iostream>
int main() {
std::pair <int, int> p = std::make_pair( 1, 2 );
std::cout << p.first << " " << p.second << std::endl;
}
You can make a vector of pairs:
typedef std::pair <int, int> IntPair;
...
std::vector <IntPair> pairs;
pairs.push_back( std::make_pair( 1, 2 ) );
pairs.push_back( std::make_pair( 3, 4 ) );
While std::pair is the best approach to use, I'm surprised nobody mentioned pre-stl solution:
struct Pair {
int first;
int second;
};
It is worrying that people think that they need boost for such a trivial problem.
精彩评论