"music4" <mu****@163.net> wrote in message news:<c6********@netnews.proxy.lucent.com>...
Greetings,
I want to STL map class. But I don't know how to use iterator. Let me state
my question by following small sample:
map<int, int> mymap;
// insert some <key,value> in mymap
iterator p = mymap::begin();
// QUESTION HERE: how to get key and value from p?
Thanks in advance!
Evan
Well, first of all, whenever you have this sort of question you should
look up the declaration of std::map in your favorite reference:
(e.g.
http://www.sgi.com/tech/stl), or even just read the header file
for your local implementation .. that should get you on the right
track.
That said, this is one of the places where the C++ STL can be a bit
confusing ... the confusion arises from the fact that:
std::map<T,U>::iterator::value_type==std::pair<T,U >
where std::pair stores the "key" (T) and "value" (U) elements as first
and second, respectively. Thus for your declaraion above, p->first
will give you the key and p->second will give you the value.
One other aspect of std::map that can be a bit confusing is that the
subscripting operator[] returns a reference to the relevant value (U),
but the find method returns an iterator. Then to make things even
more confusing, the insert method returns std::pair<iterator, bool>,
where the bool informs you of whether the insert was successful or
not. This leads to syntax like:
// for OP's declaration of mymap above
std::pair<std::map<int,int>::iterator, bool> test;
test=mymap.insert(std::pair<int,int>(101,749));
if (test.second) {
// insert succeeded -- assign new value to inserted element
(test.first)->second = 149; // !!!!
}
This can be cleaned up a bit using appropriate typedefs, but it still
takes a while to get used to the awkward syntax.
HTH, Dave Moore