Compare two map for lexicographical compare, the first non-matching element in the container determines the order - C++ STL

C++ examples for STL:map

Description

Compare two map for lexicographical compare, the first non-matching element in the container determines the order

Demo Code

#include <iostream>
#include <string>
#include <map>
using namespace std;
void show(const char *msg, map<string, int> mp);
int main() {/*from  w w w.j  a va2 s.c  o m*/
   // Declare an empty map that holds key/value pairs
   // in which the key is a string and the value is an int.
   map<string, int> m;
   // Insert characters into m. An iterator to the inserted
   // object is returned.
   m.insert(pair<string, int>("Alpha", 100));
   m.insert(pair<string, int>("Gamma", 300));
   m.insert(pair<string, int>("Beta", 200));
   // Declare an iterator to a map<string, itr>.
   map<string, int>::iterator itr;
   // Declare a reverse iterator to a map<string, itr>.
   map<string, int>::reverse_iterator ritr;
   // Create another map that is the same as the first.
   map<string, int> m2(m);
   show("Contents of m2: ", m2);
   // Determine the relationship between m and m2. This is a
   // lexicographical compare. Therefore, the first non-matching
   // element in the container determines which
   // container is less than the other.
   if(m < m2)
      cout << "m is less than m2.\n\n";
   else
      cout << "m2 is less than m.\n\n";
      return 0;
   }
   // Display the contents of a map<string, int> by using
   // an iterator.
   void show(const char *msg, map<string, int> mp) {
      map<string, int>::iterator itr;
      cout << msg << endl;
      for(itr=mp.begin(); itr != mp.end(); ++itr)
         cout << "  " << itr->first << ", " << itr->second << endl;
      cout << endl;
}

Result


Related Tutorials