Maps in C++

· by

Maps are one of the most useful datastructures in C++ and there is no excuse for not knowing it.

Here is a basic example that shows how you can use it:

#include <iostream> // cout
#include <string>

#include <map>

using namespace std;

int main() {
    map<string, string> phonebook;

    // Put some stuff in it
    phonebook["Martin"] = "(0123) 45 678";
    phonebook["Alice"] = "+(13) 37 0000";
    phonebook["Bob"]   = "+(13) 37 0000";
    phonebook["Charlie"] = "Alice";

    // Look stuff up
    cout << "The phone number of Alice is "
         << phonebook["Alice"] << endl;

    cout << "Number of phone book entries: "
         << phonebook.size() << endl;

    // Print everything
    cout << "Iterate over all phonebook entries: " << endl;
    for(map<string,string>::iterator it=phonebook.begin();
        it!=phonebook.end(); ++it) {
        cout << "\t" << (*it).first << ": " << (*it).second << endl;
    }

    // Check if entry exists:
    string person = "Bob";
    cout << "Does " << person << " have a phone number ?" << endl;
    map<string,string>::iterator it = phonebook.find(person);
    if(it != phonebook.end()) {
        //element found:
        cout << "\t" << "Yes! His number is: " << it->second << endl;
    } else {
        cout << "\t" << "No." << endl;
    }
}

See also