std::map iterator trouble

Started by
13 comments, last by Conner McCloud 19 years ago
Did you see my edit regarding reversible iterators? I'm almost certain that is the proper way to go through any container backwards, so if you have some reason not to go from the begining to end, then that's what you should do.

CM
Advertisement
If you want to iterate backwards then you need to use rend (which stands for reverse end) and similarly rbegin. They return a Reversible Iterator. You use ++ to move backwards.

std::map<std::string, GUIElement*>::iterator itr;std::map<std::string, GUIElement*>::iterator rbegin = m_Elements.rbegin();for(itr = m_Elements.rend(); itr != rbegin, ++itr) {   //etc}


Also, to communicate more clearly I would use some typedefs to simplify the code

typedef std::map<std::string, GUIElement*> ElementMap;typedef ElementMap::iterator ElementMapItr;ElementMap m_Elements;//...GUIElement *GUI::FindChildAtCoord(int x, int y){    ElementMapItr itr = m_Elements.rend();    ElementMapItr rbegin = m_Elements.rbegin();    while(itr != rbegin)    {        //etc        ++itr;    }    //etc}
Quote:Original post by petewood
You use ++ to move backwards.

Oh...that I did not know. Guess it makes sense.

Then, when using standard algorithms like find_if, could one provide rend() and rbegin() rather than begin() and end() in order to get the algorithm to iterate backwards as well?

CM
Quote:Original post by Conner McCloud
Quote:Original post by petewood
You use ++ to move backwards.

Oh...that I did not know. Guess it makes sense.

Then, when using standard algorithms like find_if, could one provide rend() and rbegin() rather than begin() and end() in order to get the algorithm to iterate backwards as well?

CM

Yes, but you would pass rbegin() as start iterator and rend() as end iterator, just line begin() is the start and end() is the end. rbegin(), altough it returns a reversible iterator to the last element, is the beginning of the reversed container, and reverse iterators are used to iterate in revserse.
Quote:Original post by Brother Bob
Quote:Original post by Conner McCloud
Quote:Original post by petewood
You use ++ to move backwards.

Oh...that I did not know. Guess it makes sense.

Then, when using standard algorithms like find_if, could one provide rend() and rbegin() rather than begin() and end() in order to get the algorithm to iterate backwards as well?

CM

Yes, but you would pass rbegin() as start iterator and rend() as end iterator, just line begin() is the start and end() is the end. rbegin(), altough it returns a reversible iterator to the last element, is the beginning of the reversed container, and reverse iterators are used to iterate in revserse.

Oh...I had this thing all sorts of backwards. I know I've used this in the past. I wonder if I did it right before, and have since forgotten, or if I just got lucky. Thanks for clearing this stuff up.

CM

This topic is closed to new replies.

Advertisement