STL Map
2002-06-20 08:34:34
Category: cpp:stl
Description: Associative array using the stl map container.
Author: detour
Viewed: 19506
Rating: (106 votes)


/* map.cpp by detour@metalshell.com
 *
 * A map is an associative array in which you
 * have a key and a value.  The key's must be
 * unique.  For a map with multiple keys you can
 * use a multimap.
 *
 * http://www.metalshell.com/
 *
 */
 
// Disable debug warning on long lines in map header
#pragma warning(disable: 4786)
 
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main() {
        map<string, int> ass_array;
 
        // Assign keys and values
        ass_array["fat"] = 0;
        ass_array["sodium"] = 45;
        ass_array["totalcarb"] = 46;
        ass_array["protien"] = 0;
 
        // Insert Value
        ass_array.insert( map<string, int>::value_type( "potassium", 25 ) );
 
        // Print value of sodium
        cout << ass_array["sodium"] << endl;
        cout << "The map has " << ass_array.size() << " entries.\n";
 
        // Iterator used to hold position in the map
        map<string,int>::iterator loc;
 
        // Returns same value as ass_array.end() if not find.
        loc = ass_array.find("sugar");
 
        if(loc != ass_array.end())
                cout << "Sugar found!\n";
        else
                cout << "No Sugar\n";
 
        return 0;
}