Maps

I'm very very new to maps and am really just trying to hash them out by myself.

If you're mapping strings to integers:

1
2
3
map <string, int> myMap;
myMap[ "zero" ] = 0;
myMap[ "one" ] = 1;


How do I print the string "zero", for instance, from myMap?

cout << myMap.at(0) << endl;

doesn't work. Nor does:

cout << static_cast<string>( myMap.at(0) ) << endl;

Do you see what I'm trying to do here?

I need access to the string using the int and the int using the string. Or just direct access to one or the other. . . It's just confusing that they're technically mapped to one another but I can't really access either of them.
I'm very very new to maps and am really just trying to hash them out by myself.
:)

Anyways, std::map isn't bidirectional. You use a key to access it's value. There isn't a direct way of getting the key mapped to a value. This is standard way maps work.

SO thread talking about it: http://stackoverflow.com/questions/5749073/reverse-map-lookup
You are trying to access the keys of the map. To get started quickly, examine this (it will print the keys):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <map>

int main()
{
    std::map<std::string, int> map;

    map["zero"] = 0;
    map["one"] = 1;

    for(std::map<std::string,int>::iterator it = map.begin(); it != map.end(); ++it) 
    {
        std::cout << it->first << "\n";

    }
}

Last edited on

I'm very very new to maps and am really just trying to hash them out by myself.
:)


Lol, that pun crossed my mind too.


#include <iostream>
#include <map>

int main()
{
std::map<std::string, int> map;

map["zero"] = 0;
map["one"] = 1;

for(std::map<std::string,int>::iterator it = map.begin(); it != map.end(); ++it)
{
std::cout << it->first << "\n";

}
}


Thank you!
Topic archived. No new replies allowed.