使用std :: generate_n填充std :: map

时间:2017-07-18 12:27:34

标签: c++ c++11 dictionary

我想使用std::map填写std::generate_n,但无法让它发挥作用。我尝试的是这些方面:

unsigned number_of_pairs{5};
std::map<std::string, std::string> my_map;
auto read_pair_from_input = [](){
    std::string key;
    std::getline(std::cin, key);
    std::string value;
    std::getline(std::cin, value);
    return std::make_pair(key, value);
};
std::generate_n(my_map.begin(), number_of_pairs, read_pair_from_input);

这给了我很长的错误,如:

In file included from /opt/wandbox/gcc-    head/include/c++/8.0.0/algorithm:62:0,
                 from prog.cc:1:
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/stl_algo.h: In instantiation of     '_OIter std::generate_n(_OIter, _Size, _Generator) [with _OIter =     std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>,     std::__cxx11::basic_string<char> > >; _Size = unsigned int; _Generator =     main()::<lambda()>]':
prog.cc:18:74:   required from here
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/stl_algo.h:4468:11: error: use     of deleted function 'std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=    (typename std::conditional<std::__not_<std::__and_<std::is_copy_assignable<_Tp>,     std::is_copy_assignable<_T2> > >::value, const std::pair<_T1, _T2>&, const     std::__nonesuch_no_braces&>::type) [with _T1 = const     std::__cxx11::basic_string<char>; _T2 = std::__cxx11::basic_string<char>;     typename std::conditional<std::__not_<std::__and_<std::is_copy_assignable<_Tp>,     std::is_copy_assignable<_T2> > >::value, const std::pair<_T1, _T2>&, const     std::__nonesuch_no_braces&>::type = const std::pair<const     std::__cxx11::basic_string<char>, std::__cxx11::basic_string<char> >&]'
  *__first = __gen();
  ~~~~~~~~~^~~~~~~~~
In file included from /opt/wandbox/gcc-head/include/c++/8.0.0/utility:70:0,
                 from /opt/wandbox/gcc-head/include/c++/8.0.0/algorithm:60,
                 from prog.cc:1:
/opt/wandbox/gcc-head/include/c++/8.0.0/bits/stl_pair.h:378:7: note:     declared here
       operator=(typename conditional<
       ^~~~~~~~

是否可以使用std::map填充std::generate_n

2 个答案:

答案 0 :(得分:24)

你想要的是std::inserter

std::generate_n(std::inserter(my_map, my_map.begin()), number_of_pairs, read_pair_from_input);

inserter会将map包装成std::generate_n可以使用的类似迭代器的结构

Demo

答案 1 :(得分:20)

std::generate_n可以像

一样实施
template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g )
{
    for( Size i = 0; i < count; i++ ) {
        *first++ = g();
    }
    return first;
}

正如您所看到的,它尝试将生成器的结果分配给迭代器。这不适用于关联容器,因为您无法修改密钥,因为这会破坏容器的结构。

你需要的是不同类型的迭代器,即你可以使用std::insert_iterator获得的std::inserter

std::generate_n(std::inserter(my_map, my_map.begin()), number_of_pairs, read_pair_from_input);