Well I'm definitely not a troll, but I noticed that you failed to finish writing the rest of what I asked about how an object can be assigned a mapping value.
It's coming. I'm doing it in bite-sized chunks so that I can make sure you understand each piece before moving on.
So, at the end of last episode, we had declared a map, much like this.
std::map<std::string, int> phoneNumbers;
or, if you've got your namespaces all nicely arranged with
using std::map;
using std::string;
it would just be
map<string, int> phoneNumbers;
This map accepts key-value pairs in which the key is a std::string and the value is an int.
So, how do we add things to the map? We have to present them already in the pair; we can't just hand over a value and then hand over an object. So, let's say we want to put the value 5557643 in, which the key "Mike". For the purposes of examples, this is Mike's phone number.
We have to put the key-value pair in as a pair. When making a pair, which uses templates (i.e. those things with the '<' and the '>' around them), you have to specifiy what the two object types in the pair are. We can make a pair like this:
pair<string, int> NewPair = pair<string, int>("Mike",5557643);
Here, we have declared the existence of an object called NewPair, and that is is of type pair<string, int>. On the right hand side, we've stated that NewPair is to be constructed as you can see there, with those initial values.
If you haven't declared that you're
using std::pair;
and
using std::string;
you would have to use
std::pair<string, int> NewPair = std::pair<std::string, int>("Mike",5557643);
Now we have a pair, called NewPair, with the key and value we wanted. Let's put this key-value pair into the map.
phoneNumbers.insert(NewPair);
And that's a map made, with a key-value pair in it. You could add more key-value pairs:
NewPair = pair<string, int>("Mike",5557643);
phoneNumbers.insert(NewPair);
NewPair = pair<string, int>("Jeff",5557648);
phoneNumbers.insert(NewPair);
NewPair = pair<string, int>("Spoonlicker",5557649);
phoneNumbers.insert(NewPair);
There are other ways to make a pair, and other ways to put the data in, but this is one way that should hopefully make it clear how to use it and how to store data in a map. If this is clear, we can cover how to fetch the value back again from the map.
Thus far, our working code looks like this:
#include <iostream>
#include <map>
int main()
{
using std::pair;
using std::string;
std::map<std::string, int> phoneNumbers;
std::pair<std::string, int> NewPair = std::pair<std::string, int>("Mike",5557643);
phoneNumbers.insert(NewPair);
NewPair = pair<string, int>("Jeff",5557648);
phoneNumbers.insert(NewPair);
NewPair = pair<string, int>("Spoonlicker",5557649);
phoneNumbers.insert(NewPair);
return 0;
}
We made a map object, then we made pairs and put them into the map one at a time. Fetching them back comes next, if that's all clear. Fetching them back uses "iterators", which you might not like very much.