943,549 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 518
  • C++ RSS
Aug 7th, 2009
0

map question

Expand Post »
How do you erase an element thats inside a map. Not the key but the element the key is pointing to? This doesnt seem to be doing what i want it to.

C++ Syntax (Toggle Plain Text)
  1. map<int, vector<int> > my_map;
  2. map<int, vector<int> >::iterator it;
  3.  
  4. void erase(int num)
  5. {
  6.  
  7. for(map::iterator item=my_map.begin();item != my_map.end())
  8. {
  9. if(it == num)
  10. my_map.erase(it++);
  11. else
  12. ++it;
  13. }
  14. }
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
JackDurden is offline Offline
92 posts
since Jun 2008
Aug 7th, 2009
1

Re: map question

looks like there's a couple things, I don't think that would even compile: comparing a map<int, vector<int> >::iterator to an int inside your loop doesn't seem safe to me. As well as not declaring the map type for your iterator.

anyway, see if this is a good starting point:

c++ Syntax (Toggle Plain Text)
  1. map<int, vector<int> > my_map; //I assume these are global or in a class, as you had it
  2. map<int, vector<int> >::iterator it;
  3.  
  4. void erase(int num)
  5. {
  6. for(it = my_map.begin(); it != my_map.end(); it++)
  7. {
  8. if((*it).first == num)
  9. {
  10. my_map.erase(it);
  11. break;
  12. }
  13. }
  14. }

I think that's what you were going for, hope that's helpful

~J
Reputation Points: 76
Solved Threads: 15
Junior Poster
jesseb07 is offline Offline
111 posts
since Dec 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Loading and Setting text
Next Thread in C++ Forum Timeline: Trigger sendmessage?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC