[solved][STL] is there an inserter (insert iterator) for map?

Jul 26, 2008 at 7:37am
Suppose I have a template function which takes an OutputIterator of pair<X,Y>s which should now be used to fill a std::map<X,Y>:
1
2
3
4
5
6
7
8
9
10
11
12
<template typename OutputIterator>void f(OutputIterator result)
{
    for(int i=0; i<10; ++i)
        result++ = std::pair<X,Y>(X(...), Y(...));
}

void g()
{
    std::map<X,Y> m;
    f(std::back_inserter(m));
//              ^^ does not exist! (map::push_back does not exist)
}

Obviously, there is no {back,front}_inserter for std::map, since it does not have the operations push_{front,back}. Is there any way to use the function interface mentioned above nonetheless?

Thanks for any advance!
Last edited on Jul 27, 2008 at 10:33am
Jul 26, 2008 at 4:04pm
Just use a regular inserter:
1
2
3
4
5
6
7
8
9
10
11
template <typename OutputIterator>
void f( OutputIterator result )
{
    ...
}

void g()
{
    std::map <X,Y> m;
    f( std::inserter( m, m.begin() ) );
}

Hope this helps.
Jul 27, 2008 at 2:41am
Wait. Isn't std::map just a balanced binary search tree? There's no point in inserting something in the middle, since it's an sorted structure to begin with. If you use
 
map[key]=value; //'key' didn't previously exist in the map. 

it will insert sorted the key into the map.
Jul 27, 2008 at 2:50am
Yes, but you can't use [] with STL (or other generic) algorithms.
For associative containers insert() sticks the item in the correct spot in the tree, so any iterator you supply to start will work just fine.
Last edited on Jul 27, 2008 at 2:51am
Jul 27, 2008 at 8:05am
Thanks, I somehow managed to overlook the plain inserter, how stupid. I could add, to my defense, that I usually don't use maps... Thanks again.
Topic archived. No new replies allowed.