The map is an associative array. Normally you would use it to look up some data item B based on some key A, where the key A doesn't need to be numeric (but does need to be orderable, that is, comparable, to other As).
Consider the common:
std::map< std::string, double > clAgeMap;
std::string clName1="Gary";
std::string clName2="Mark";
std::string clName3="Sarah";
clAgeMap[clName1]=25.0;
clAgeMap[clName2]=26.0;
clAgeMap[clName3]=31.0;
(yes, I know I could have made that more compact).
The index is some sort of comparable key.
You can extract the values in the same way:
std::cout << clName1 << " has age "
<< clAgeMap[clName1] << std::endl;
std::cout << clName2 << " has age "
<< clAgeMap[clName2] << std::endl;
std::cout << clName3 << " has age "
<< clAgeMap[clName3] << std::endl;
Iterating through them could be done if you knew each of the keys beforehand, obviously. But because the keys are not necessarily sequential integers, you can't just index them numerically (unless your keys happen to all be integers between 0 and n-1, and then why would you be using a map?).
All of the STL containers have iterators that enable you to more universally process the elements one by one, even the vector type which acts like an array. Consider, for some 'ContainerType' called 'container':
std::ContainerType::iterator iter;
for (iter=container.begin();
iter!=container.end();
++iter)
std::cout << *iter << std::endl;
normally works on container elements. iter is an object which acts like a pointer, and moves from the beginning to end of the container using pointer-like logic.
This won't _quite_ work on a map. The reason is that the elements of a map are key/data pairs. In fact, the elements are precisely:
std::pair< Key, Data >
for some Key and Data. In my example, its:
std::pair< std::string, double >
and each pair is basically equivalent to:
struct pair
{
Key first;
Data second;
};
for the sake of argument. Then, the loop gets changed to:
std::map< std::string, double >::iterator iter;
for (iter=container.begin();
iter!=container.end();
++iter)
std::cout << iter->first << '/' << iter->second << std::endl;
Easy as pie, right?
Iterators are an abstraction on pointers and indices. They work the same way (well, almost) no matter how the internal structure of the container works.
|