Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c++ - How to insert into std::map?

Is there a std iterator I could use to insert elements into std::map using a std algorithm (for example std::copy) ?

I need a container to link one object to a string, and I thought about using std::map. Is there a better container? Forgot to say - items needs to be sorted.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think what the OP is looking for is std::inserter(mymap, mymap.end())

so you can do:

std::copy( inp.begin(), inp.end(), std::inserter(mymap, mymap.end()) );

The input types must be a pair type that your map takes, otherwise your algorithm would need to be std::transform with a function/functor to convert the input type into such a std::pair.

inserter is not actually an iterator but a templated function that produces an iterator (std::insert_iterator, which is a templated type but the type is automatically resolved in the function call).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...