Page 1 of 1

STL Maps A simple broken-down "How to" Rate Topic: ***** 1 Votes

#1 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1385
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Posted 13 July 2008 - 04:18 PM

*
POPULAR

STL Containers: Maps

What is a map?
A map is a super-cool and useful method of storing data. It's kind of a cross between a vector and an array. It's just that cool.

How does a map work?
Basically, when we create a map, we give it two datatypes, as opposed to one (when we use a vector). The first is used as the key, which is basically used like when we use arrays. The second is the value, which is the actual value that this member will store. Hard to explain, simple to use. So don't worry ;)
In summary, a map is like an array, but think of the array syntax when giving a value to a part of an array:
grades[4] = 'A';
Rather than using a meaningless key, wouldn't it be cool if we could have something like:
grades["Danny"] = 'A';
Exactly! So that's basically what a map is. Now, onto the actual creation of one...

Including stuff - what needs to be included when we make a map?
#include <iostream>
#include <iomanip>
#include <map>

using namespace std;
Now, iostream and iomanip are only being included so that I can show you what's going on. In other words, all you really need to include is #include <map> (And don't forget that we need to be using std::map; too!)

Onwaaaaaard!
What next? Well, I've written a function to display it using iterators (another of my tutorials) :wink:
Here it is, totally annotated in all it's glory:
void display (map <string,char> grades)
{
    cout << "\tTotal size: " << grades.size() << endl; /* Output the size */
    /* Create an iterator, much like vector iterators */
    map <string, char>::iterator it;
    for (it = grades.begin(); it != grades.end(); ++it)
        /* Output first (which is the string) and second (which is the char) */
        cout << setw(10) << it->first << setw(5) << it->second << endl;

    cout << endl; /* Print a new line */
}
It looks a little confusing, but it should make sense by the end of this tutorial! Basically, I use setw() (from iomanip) to make the output tidy, it's nothing majorly important, just remember that first and second are important keywords! In this case, first refers to the string, and second refers to the grade.

Now for main. I'm hoping you understand int main () { so I'm gonna skip that bit ;)

Adding stuff to our map
This is relatively simple, really. Time for a chunk of code, heavily annotated explaining why maps are so awesome:
    cout << "Populating map..." << endl;
    map <string, char> grades; /* Create a map with string as a referencer and char as the storage */
    grades["Danny"] = 'A'; /* This is how we add values to a map */
    grades["Kayleigh"] = 'A'; /* Basically, it is like an array, but cooler */
    grades["Joe"] = 'F'; /* We get to use any data type we like as the access key */
    grades["Brad"] = 'C'; /* As opposed to using 'int' all the time wih an array */

    cout << "Before any modifications:" << endl;
    display (grades); /* Call my function to display the map */
Aren't they great? :wub:
Rather than using a highly unuseful index like grades[0] = 'A'; we've actually gone and given it a meaningful reference! Pretty cool, huh? Well, you ain't seen nuffin yet!

Deleting bits and bobs from a map
Super simple. Just erase() what you find() like so:
    /* erase() will delete the member of the map that is being passed */
    /* find() will find the data being stored under the key, and return the iterator position */
    grades.erase (grades.find("Joe"));
    cout << "After deleting a value:" << endl;
    display (grades); /* Call my function to display the map */
Joe is unimportant, so I deleted him ;)

Checking if something exists within a map
Again, this is really simple. Basically, we call count() to see if there's something in the map or not, like so:
    /* Perform a couple of checks to see what is in the map */
    if (grades.count("Danny")) /* if "Danny" is in the map */
         cout << "Danny is a member of grades" << endl;
    else cout << "Danny is not a member of grades" << endl;
    if (grades.count("Joe")) /* remember we deleted him! */
         cout << "Joe is a member of grades" << endl;
    else cout << "Joe is not a member of grades" << endl;


Emptying a map
For those destructive people, we can delete everything stored in a map at once, very simple again! Wow, maps are so great!
    /* clear() does exactly what it says on the tin. It completely clears all data from the map */
    grades.clear ();
    cout << "After clearing the map:" << endl;
    display (grades);

Don't forget to close off main! }

And there we have it! A simple demostration of how maps can be used. For those completists out there, here is the entire code which I used in this tutorial:
#include <iostream>
#include <iomanip>
#include <map>

using namespace std;

void display (map <string,char> grades)
{
    cout << "\tTotal size: " << grades.size() << endl; /* Output the size */
    /* Create an iterator, much like vector iterators */
    map <string, char>::iterator it;
    for (it = grades.begin(); it != grades.end(); ++it)
        /* Output first (which is the string) and second (which is the char) */
        cout << setw(10) << it->first << setw(5) << it->second << endl;

    cout << endl; /* Print a new line */
}

int main ()
{
    cout << "Populating map..." << endl;
    map <string, char> grades; /* Create a map with string as a referencer and char as the storage */
    grades["Danny"] = 'A'; /* This is how we add values to a map */
    grades["Kayleigh"] = 'A'; /* Basically, it is like an array, but cooler */
    grades["Joe"] = 'F'; /* We get to use any data type we like as the access key */
    grades["Brad"] = 'C'; /* As opposed to using 'int' all the time wih an array */

    cout << "Before any modifications:" << endl;
    display (grades); /* Call my function to display the map */

    /* erase() will delete the member of the map that is being passed */
    /* find() will find the data being stored under the key, and return the iterator position */
    grades.erase (grades.find("Joe"));
    cout << "After deleting a value:" << endl;
    display (grades); /* Call my function to display the map */

    /* Perform a couple of checks to see what is in the map */
    if (grades.count("Danny")) /* if "Danny" is in the map */
         cout << "Danny is a member of grades" << endl;
    else cout << "Danny is not a member of grades" << endl;
    if (grades.count("Joe")) /* remember we deleted him! */
         cout << "Joe is a member of grades" << endl;
    else cout << "Joe is not a member of grades" << endl;

    cout << endl; /* Add a bit of white space */

    /* clear() does exactly what it says on the tin. It completely clears all data from the map */
    grades.clear ();
    cout << "After clearing the map:" << endl;
    display (grades);

    cin.get ();
    return EXIT_SUCCESS;
}


For more information, visit the documentation about maps on http://www.cplusplus.com/

Happy coding!

Is This A Good Question/Topic? 7
  • +

Replies To: STL Maps

#2 NoviceC++Programmer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 28-December 08

Posted 10 January 2009 - 11:05 PM

Coooliooooooo....... :^:

perfectly explained. I've never seen such an intresting and simple tut on maps. (though i've not seen so many tuts :pirate: )

thanks for this and cheers.
Was This Post Helpful? 0
  • +
  • -

#3 krzysz00  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 83
  • Joined: 25-February 09

Posted 03 May 2009 - 07:09 AM

cool
Was This Post Helpful? 0
  • +
  • -

#4 Guest_Allen*


Reputation:

Posted 30 April 2010 - 06:20 PM

Is it possible two have 2 keys for a map?
Was This Post Helpful? 0

#5 Guest_hontou no chikara*


Reputation:

Posted 22 May 2010 - 03:13 AM

i use the map container to populate game states in my noob 2d game :)
as u can see find is powerfull

m_gameStateMap["Playing"] = new GSPlaying;
	SetGameState( "Playing" );


void Game::SetGameState( std::string gameStateTitle )
{
	GameStateMap::iterator it = m_gameStateMap.find( gameStateTitle );
	if( it != m_gameStateMap.end() )
	{
		m_gameState = it->second;
	}
}

Was This Post Helpful? 0

#6 c0d3prada  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 6
  • Joined: 16-November 10

Posted 17 November 2010 - 08:08 PM

very useful tutorial and it's much like associative arrays
Was This Post Helpful? 0
  • +
  • -

#7 schm0e  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-December 13

Posted 03 December 2013 - 05:22 PM

This is how a tutorial should read.

Thanks for answering my question and not wasting my time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1