Professional C__ - Marc Gregoire [208]
The pair Utility Class
Before learning about the associative containers, you must become familiar with the pair class, which is defined in the // Two-argument constructor and default constructor pair pair // Can assign directly to first and second myOtherPair.first = "hello"; myOtherPair.second = 6; // Copy constructor pair // operator< if (myPair < myOtherPair) { cout << "myPair is less than myOtherPair" << endl; } else { cout << "myPair is greater than or equal to myOtherPair" << endl; } // operator== if (myOtherPair == myThirdPair) { cout << "myOtherPair is equal to myThirdPair" << endl; } else { cout << "myOtherPair is not equal to myThirdPair" << endl; } Code snippet from Pair\PairTest.cpp The output is as follows: myPair is less than myOtherPair myOtherPair is equal to myThirdPair The library also provides a utility function template, make_pair(), that constructs a pair from two values. For example, you could use it like this: pair Code snippet from Pair\PairTest.cpp Of course, in this case you could have just used the two-argument constructor. However, make_pair() is more useful when you want to pass a pair to a function. Unlike class templates, function templates can infer types from parameters, so you can use make_pair() to construct a pair without explicitly specifying the types. You can also use make_pair() in combination with the C++11 auto keyword as follows: auto aSecondPair = make_pair(5, 10); Code snippet from Pair\PairTest.cpp Using plain old pointer types in pairs is risky because the pair copy constructor and assignment operator perform only shallow copies and assignments of pointer types. However, you can safely store smart pointers like shared_ptr in your pair. map The map is one of the most useful containers, defined in the