Associative containers and iterators

A

anonymous

I have a function that returns a map<string, vector<int> >.
Inside the function I load the map with this instruction:

loc_map["hello"].push_back(1);

I would like to remove the output data structure and to use a template
function with iterators.

My idea is to use an iterator in this way:

template <class Out>
void my_fun( Out m ) {...}

and call the function:

my_fun(back_inserter(my_map));

My problem is: Is it possible to write the instruction
loc_map["hello"].push_back(1); using the parameter m?

Thanks
 
J

James Kanze

I have a function that returns a map<string, vector<int> >.
Inside the function I load the map with this instruction:
loc_map["hello"].push_back(1);

I would like to remove the output data structure and to use a
template function with iterators.
My idea is to use an iterator in this way:
template <class Out>
void my_fun( Out m ) {...}
and call the function:
my_fun(back_inserter(my_map));

My problem is: Is it possible to write the instruction
loc_map["hello"].push_back(1); using the parameter m?

A back_insert_iterator always inserts at the end, using
push_back. An associative container cannot allow the user to
insert where he wants; it must insert where it wants. Thus, a
back_insert_iterator cannot be used with it.

It's somewhat of an abuse, but you can use a normal
insert_iterator, passing it the end iterator of the map when you
construct it. In the case of map, of course, you'll have to
write a map<>::value_type to it. But frankly, what's wrong with
just passing the function a reference to the map, and letting it
do its job normally? Maps aren't containers, regardless of what
the standard says, and trying to use them like a container is
generally misleading.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top