Sort a vector of pairs : pair « map multimap « C++ Tutorial






#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <utility>

using namespace std;

typedef pair<int,string> Pair;

inline bool less_than_second( const Pair& b1, const Pair& b2 ){
   return b1.second < b2.second;
}

int main(){
   const char* names[] = { "A","B", "C", "D","E" };
   const int values[] = { 18, 20, 26, 30, 41 };
   const int num_pairs = sizeof( names ) / sizeof( names[0] );

   vector<Pair> pair( num_pairs );
   transform( values, values+num_pairs, names,pair.begin(), make_pair<int,string> );

   sort( pair.begin(), pair.end() );

   sort( pair.begin(), pair.end(), less_than_second );

   vector<Pair>::const_iterator pair_end = pair.end();
   for( vector<Pair>::const_iterator i = pair.begin();
      i != pair_end; ++i )
   cout << i->second << " - $" << i->first << " values\n";
}








23.17.pair
23.17.1.Assign value directly to first and second
23.17.2.Default constructor for pair
23.17.3.Using copy constructor to create another pair
23.17.4.Use operator of less than (<)
23.17.5.Use operator of equal (=)
23.17.6.Use make_pair() function to create a pair
23.17.7.Create a pair object that will contain the result of a call to insert()
23.17.8.Create a pair object that holds the result of insert()
23.17.9.Using a Pair to store int and string
23.17.10.Vector of pair
23.17.11.Sort a vector of pairs