views:

965

answers:

4

Hello all,

I have

std::list<multimap<std::string,std::string>::iterator> >

Now i have new element:

multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test")

I want to avoid the need to set temp multimap and do insert to the new element just to get its iterator back so i could to push it back to the:

std::list<multimap<std::string,std::string>::iterator> >

can i somehow avoid this creation of the temp multimap. Thanks

+1  A: 

You have not specified the data type that you store in your list. Anyway, assuming that you want to add the value(s) pointed to by a particular key, you can call list.insert(*mapIter).

multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test")

You need to add this to your multimap via map.insert. This function returns an iterator. You can then safely add this iterator to your list.

std::list<multimap<std::string,std::string>::iterator> yourlist;
// ....
multimap<std::string,std::string>::iterator itr = 
                               yourmultimap.insert(aNewMmapValue);
yourlist.insert(itr);
dirkgently
+2  A: 

You need to insert the key-value pair into a multimap before getting an iterator for it.

An iterator does not work by itself. If you are storing iterators from several different multimaps you probably need to store more than just an iterator in the list.

Perhaps:

  1. a pair<multimap<std::string,std::string>::iterator, multimap<std::string,std::string>::iterator> where first is the iterator and second is the end-iterator.

  2. a pair<multimap<std::string,std::string>::iterator, multimap<std::string,std::string>*> where first is the iterator, and second is a pointer to the multimap that the iterator belongs to.

  3. some other kind of solution.

EDIT: I concur with Mykola Golubyev: It is often a bad idea to store iterators for a longer period of time, as the iterators may be invalidated.

dalle
A: 

The type std::multimap<std::string,std::string>::iterator is an iterator to a std::pair<const std::string, std::string> stored in a std::multimap. If the element isn't stored in a multimap, it can't be referred to through a mulitmap iterator.

You may want to store use a std::list<std::pair<std::string,std::string> > instead.

Joe Gauterin
A: 

Don't store iterators. Use either const iterators or better way is store the pointers to the elements in the map.

siva