Public Group

copy does not support map

This topic is 4108 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I found std::copy can copy set or vector. but how can I copy map ?r there any function available?

Share on other sites
Just like any other container, std::map provides access to its elements as a sequence bounded by iterators.

std::copy(the_map.begin(),the_map.end(),destination);

Share on other sites
copy(the_map.begin(),the_map.end(),ostream_iterator<value_type>(cout," ")
can I do this?
What I mean is what is output of copy? the_map value or the_map pair<key,value>?

Share on other sites
test it in your compiler if you really want to know

Share on other sites
The value_type of std::map is std::pair< Key const, Value >, so to just copy the value, you need to select second:

template< size_t which >struct select_element_from_pair {};template<>struct select_element_from_pair< 1 > {  template< class T1, class T2 >  T1 operator()( std::pair< T1, T2 > const & p ) const {    return p.first;  }};template<>struct select_element_from_pair< 2 > {  template< class T1, class T2 >  T2 operator()( std::pair< T1, T2 > const & p ) const {    return p.second;  }};std::transform(    the_map.begin(),    the_map.end(),    destination,    select_element_from_pair< 2 >() );

You could also write an iterator adapter (see boost::transform_iterator) that selects the appropriate element from the pair. TR1 defines a function get() which works like select_element_from_pair.

jfl.

Share on other sites
Quote:
 Original post by jflangloisThe value_type of std::map is std::pair< Key const, Value >, so to just copy the value, you need to select second:*** Source Snippet Removed ***

Interestingly, the STL originally defined select1st and select2nd for this purpose (templated, expecting members named 'first' and 'second'; so that you could do generic programming if you had a struct defining 'first', 'second' and 'third' for some reason), but they didn't make the cut for the C++ standard library.

Share on other sites
Quote:
Original post by Zahlman
Quote:
 Original post by jflangloisThe value_type of std::map is std::pair< Key const, Value >, so to just copy the value, you need to select second:*** Source Snippet Removed ***

Interestingly, the STL originally defined select1st and select2nd for this purpose (templated, expecting members named 'first' and 'second'; so that you could do generic programming if you had a struct defining 'first', 'second' and 'third' for some reason), but they didn't make the cut for the C++ standard library.

That's what was prodding me in the back of my brain! I remember seeing that, probably in SGI's reference, which I've since abandoned.

jfl.

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• Forum Statistics

• Total Topics
631782
• Total Posts
3002324
×