-
Working with 'map'
It's me again,
Last night I start to learn about map. Feel it is so useful when I want to work with data basket without using a database. Because no need to worried about data set, data connections and stuff.
Anyway, I got the knowledge about map in useful level. But I have a point that mess on it. I'll explain it in this way.
First I've define the data map and insert some value as follows.
Code:
map<string, int> data_map; // map definitions
// Inserting values
data_map["One"] = 1;
data_map["Two"] = 2;
data_map["Three"] = 3;
Now I want to allow user to check there is available his/her entry. I've done it as follows.
Code:
string map_entry;
cout << "Enter a word:\t";
getline(cin, map_entry);
if(data_map.find(map_entry) != data_map.end())
{
cout << "Your entry have the value of " << data_map[map_entry] << endl;
}
else
{
cout << "Your entry is not in the data_map" << endl;
}
It's ok to me. Then I've try to work it out with iterator, as follows.
Code:
map<string, int>::iterator data_map_iterator;// data_map iterator
if((data_map_iterator = data_map.find(map_entry)) != data_map.end())
{
cout << "Your entry is " << data_map_iterator->first << " and the entry value is " << data_map_iterator->second << endl;
}
else
{
cout << "Your entry is not in the data_map" << endl;
}
In simply what is the real use of iterator and what is the effect of it my two code segments.
-
Re: Working with 'map'
An iterator is just a safer pointer..
They are.. how would you say.. a templated pointer. They point to whatever type the template specifies. In your case.. a map object.
In the second segment.. obviously (as you've used it in such a way).. using an iterator allows you access to both the Key and Value of the map item (second snippet). Whereas, referencing it by Key, only gives you the Value (first snippet)
chem
-
Re: Working with 'map'
Yep chem, I think so. When I get use to work in the way of first segment, some instances it is dull to work with both key and the value.
But using iterator is so easy to me.
Finally, what is your suggestion, the best way to work with map is use of iterator. I'm saying that, the best way, not the only way...
-
Re: Working with 'map'
Using iterators is the standard.. all standard library containers (I'm pretty sure every single one of them) have iterator types.. Lists, Vectors.. even strings, have iterators, const_iterators.. etc.
chem
-
Re: Working with 'map'
Ok, as you said working with the standard way should be the best. Thanks chem. Now I've clear it.