John wrote:
v.reserve(tmap.size());
copy(tmap.begin(), tmap.begin() + tmap.size(), v.begin());
but my tmap is map<K,I> and my vector v is vector<K>
Is this copy right?
I don't think that std::copy is appropriate here. The value_type of
your map is std::pair<K, I>, while the value_type of your vector is just
K. The former cannot be assigned to the latter. What you are looking
for is std::transform, which let's you provide a function that will
transform the pair into the appropriate value. Here is an example,
using types K and I as you did. Note that select1st and select2nd are
based on the descriptions given here:
http://www.sgi.com/tech/stl/table_of_contents.html
-Alan
#include <iostream>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
template <typename Pair>
struct select1st
{
typedef Pair argument_type ;
typedef typename Pair::first_type result_type ;
const result_type &
operator()(const argument_type &p) const
{
return p.first ;
}
} ;
template <typename Pair>
struct select2nd
{
typedef Pair argument_type ;
typedef typename Pair::second_type result_type ;
const result_type &
operator()(const argument_type &p) const
{
return p.second ;
}
} ;
int main()
{
typedef const char * K ;
typedef int I ;
std::map<K, I> m ;
std::vector<K> vk ;
std::vector<I> vi ;
// Put some values into the map.
m["key1"] = 1 ;
m["key2"] = 2 ;
m["key3"] = 3 ;
m["key4"] = 4 ;
// Copy the keys to the vector.
vk.reserve(m.size()) ;
std::transform(m.begin(), m.end(), std::back_inserter(vk),
select1st<std::map<K, I>::value_type>()) ;
// Print the vector.
std::copy(vk.begin(), vk.end(),
std::ostream_iterator<K>(std::cout, "\n")) ;
// Copy the values to the vector.
vi.reserve(m.size()) ;
std::transform(m.begin(), m.end(), std::back_inserter(vi),
select2nd<std::map<K, I>::value_type>()) ;
// Print the vector.
std::copy(vi.begin(), vi.end(),
std::ostream_iterator<I>(std::cout, "\n")) ;
return 0 ;
}