Взять детали с карты и сохранить их в другую? - PullRequest
0 голосов
/ 02 июня 2011

У меня есть такая карта

map<string, pair< pair<int, int>, string> >

Какой самый простой способ получить только две строки и сохранить в другую карту, подобную этой

map<string, string>

?Я имею в виду, есть ли другой способ, кроме как что-то вроде этого?

    map<string, pair< pair<int, int>, string> >  info;
    map<string, pair< pair<int, int>, string> >::iterator i;
    map<string, string> something;


    for(i=info.begin(); i!=info.end(); ++i)
        something[*i).first] = ((*i).second).second;

Ответы [ 3 ]

2 голосов
/ 02 июня 2011

Во-первых, я бы определил правильный тип:

struct Mapped
{
    int someSignificantName;
    int anotherName;
    std::string yetAnother;
};

Практически нет случаев, когда std::pair является приемлемым решением. (кроме быстрых взломов и тестов). Учитывая это, вы определяете отображение функциональный объект:

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 );
    }
};

, затем используйте std::transform:

std::transform( in.begin(), in.end(),
                std::inserter( out, out.end() ),
                Remap() );
1 голос
/ 02 июня 2011

Самый простой способ - написать простой цикл for, который просто работает.

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 ) );
}

Хитрый путь («однострочник»):

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 путь:

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 ) ); } );
1 голос
/ 02 июня 2011
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;
}

Кстати, EWTYPE.

...