Taking details from a map and saving it into another?
I have a map like this
map<string, pair< pair<int, int>, string> >
what is the easiest way to get only the two strings and save into another map like this
map<string, string>
? I mean is there another way other than something like this??
map<string, pair< pair<int, int>, string> > info;
map<string, pair< pair<int, int>, string> >::iterator开发者_StackOverflow i;
map<string, string> something;
for(i=info.begin(); i!=info.end(); ++i)
something[*i).first] = ((*i).second).second;
First, I'd define a proper type:
struct Mapped
{
int someSignificantName;
int anotherName;
std::string yetAnother;
};
There are almost no cases where std::pair
is an acceptable solution
(except for quick hacks and tests). Given that, you define a mapping
functional object:
struct Remap
: std::unary_operator<std::pair<std::string, Mapped>,
std::pair<std::string, std::string> >
{
std::pair<std::string, std::string> operator()(
std::pair<std::string, Mapped> const& in ) const
{
return std::make_pair( in.first, in.second.yetAnother );
}
};
, then use std::transform
:
std::transform( in.begin(), in.end(),
std::inserter( out, out.end() ),
Remap() );
map<string, pair< pair<int, int>, string> > map1 /* = ... */;
map<string, string> map2;
BOOST_FOREACH (const pair<string, pair< pair<int, int>, string> > >& it, map1) {
map2[it.first] = it.second.second;
}
By the way, EWTYPE.
The easiest way is to write simple for-loop that just works.
typedef pair<pair<int, int>, string> strange_pair_t;
typedef map<string, strange_pair_t> strange_type_t;
strange_type_t src_map;
map<string, string> dst_map;
for(strange_type_t::const_iterator it = src_map.begin(); it!=src_map.end(); ++it)
{
dst_map.insert( make_pair( it->first, it->second.second ) );
}
The tricky way ("one-liner"):
std::transform( src_map.begin(), src_map.end(), inserter(dst_map, dst_map.end()),
boost::lambda::bind(
boost::lambda::constructor<pair<string,string>>(),
boost::lambda::bind( &strange_type_t::value_type::first, boost::lambda::_1 ),
boost::lambda::bind( &strange_pair_t::second, boost::lambda::bind( &strange_type_t::value_type::second, boost::lambda::_1 ) )
)
);
C++0x way:
for_each( src_map.begin(), src_map.end(), [&dst_map](const strange_type_t::value_type& value) {
dst_map.insert( make_pair( value.first, value.second.second ) ); } );
精彩评论