C++ Associative Container - Map iterator example

in #cpp6 years ago

Maps

A stores elements that contain both a 'key' and a 'value'. An elements key is used to locate the element in the map, and the value holds the information for that key. By default maps are ordered sequentially by their key. A reference to all of its member functions can be found here: http://www.cplusplus.com/reference/map/map/

Ex Code
#include <iostream>
#include <map>
#include <iterator>
#include <string>

using namespace std;

void map_ex() {
    map<string, int> students;

    cout << "MAP ITERATORS\n";

    students.emplace("Zach", 88);
    students.emplace("Mary", 93);
    students.emplace("Will", 74);
    students.emplace("Ari", 81);

    cout << "\nIterate through each element\n";
    map<string, int>::iterator itr;
    for(itr = students.begin(); itr != students.end(); ++itr) {
        /* 'first' refers to the key */
        /* 'second' refers to the value */
        cout << itr->first << " : " << itr->second << endl;
    }
}

int main() {
    map_ex();
    return 0;
}


Output
MAP ITERATORS

Iterate through each element
Ari : 81
Mary : 93
Will : 74
Zach : 88
Sort:  

Great post.I voted it up and hope to see soon more !!!!!

Thanks, there will be more to come.