Or login with:
#include <utility> namespace std { template < class T, class U > struct pair { T1 first; T2 second; // constructors }; }
<T1,T2> is a heterogeneous pair: it holds one object of type T1 and one of type T2. A pair is not actually a model of Container, though, because it does not support the standard methods (such as iterators) for accessing the elements of a Container.
The STL pair can be assigned, copied and compared. The array of objects allocated in a map or hash_map are of type pair by default, where all the "first" elements, T1 act as the unique keys, each associated with their 'second' value objects, T2.
Short example:
pair<string, int> pr1; // declare a pair variable pair<string, int> pr2("John", 7); // declare and initialize with constructor
namespace std { template < class T1, class T2 > bool operator== (const pair<T1,T2>& x, const pair<T1,T2>& y) return x.first == y.first && x.second == y.second; }In a comparison of pairs, the first value has higher priority. If the first values of two pairs differ, the result of their comparison is used as the result of the comparison of the whole pairs. If the first values are equal, the comparison of the second values yields the result:
namespace std { template < class T1, class T2 > bool operator< (const pair<T1,T2>& x, const pair<T1,T2>& y) { return x.first < y.first || (!(y.first < x.first) && x.second < y.second); } }The other comparison operators are defined accordingly.
namespace std{ template < class T1,class T2 > pair<T1,T2> make_pair (T1 x, T2 y) return (pair<T1,T2>(x,y)); }Short example:
// by using \c{make_pair()} you can write std::make_pair(10, 'D') // instead of std::pair<int,char>(10, 'D')
#include <iostream> #include <utility> #include <string> using namespace std; int main () { pair <string,double> product1 ("tomatoes",3.25); pair <string,double> product2; pair <string,double> product3; product2.first = "lightbulbs"; // type of first is string product2.second = 0.99; // type of second is double product3 = make_pair ("shoes",20.0); cout <<"The price of "<<product1.first<<" is "<<product1.second<<" dollars."<<"\n"; cout <<"The price of "<<product2.first<<" is "<<product2.second <<" dollars."<<"\n"; cout <<"The price of "<<product3.first<<" is "<<product3.second<<" dollars."<<"\n"; return 0; }
You must login to leave a messge