c++ - 使用 std::generate 的随机 unordered_multimap

标签 c++ c++17 stl-algorithm unordered-multimap

我正在尝试使用以下代码生成大小为 10 的随机 unordered_multimap:

#include <algorithm>
#include <unordered_map>
#include <cstdlib>

int main()
{
    auto m = std::unordered_multimap<int, int>(10);
    std::generate(
        m.begin(),
        m.end(),
        [](){return std::pair{std::rand(),std::rand()};}
    );
} 

但是编译不会报错

 In file included from /usr/include/c++/7/algorithm:62:0,
                 from main.cpp:2:
/usr/include/c++/7/bits/stl_algo.h: In instantiation of ‘void std::generate(_FIter, _FIter, _Generator) [with _FIter = std::__detail::_Node_iterator<std::pair<const int, int>, false, false>; _Generator = main()::<lambda()>]’:
<span class="error_line" onclick="ide.gotoLine('main.cpp',11)">main.cpp:11:5</span>:   required from here
/usr/include/c++/7/bits/stl_algo.h:4438:11: error: use of deleted function ‘std::pair<_T1, _T2>& std::pair<_T1, _T2>::operator=(typename std::conditional, std::is_copy_assignable<_T2> > >::value, const std::pair<_T1, _T2>&, const std::__nonesuch_no_braces&>::type) [with _T1 = const int; _T2 = int; typename std::conditional, std::is_copy_assignable<_T2> > >::value, const std::pair<_T1, _T2>&, const std::__nonesuch_no_braces&>::type = const std::pair&]’
  *__first = __gen();
  ~~~~~~~~~^~~~~~~~~
In file included from /usr/include/c++/7/utility:70:0,
                 from /usr/include/c++/7/unordered_map:38,
                 from main.cpp:1:
/usr/include/c++/7/bits/stl_pair.h:378:7: note: declared here
       operator=(typename conditional<
       ^~~~~~~~

:是否可以使用std::generate 生成随机unordered_multimap?如果不是,最好的方法是什么?

PS:我知道我应该使用 std::default_random_engine 而不是 std::rand,我在真实代码中这样做,这只是为了演示目的.

最佳答案

您可以使用 std::insert_iterator类模板来实现你正在寻找的东西:

auto m = std::unordered_multimap<int, int>{};

std::generate_n(std::insert_iterator(m, m.begin()),
     10, [](){ return std::pair{std::rand(),std::rand()}; }); 

关于c++ - 使用 std::generate 的随机 unordered_multimap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441262/

相关文章:

c++ - 使用 STL 算法的命名空间和用户定义的运算符

c++ - 为什么 fill_n() 不适用于 vector.reserve()?

c++ - 接口(interface)和公共(public)方法

c++ - 将一个 DLL 链接到另一个 DLL 的正确步骤

c++ - 如何使用 C++ 流输出小数点后 3 位数字?

c++ - 如何关闭标准智能指针的自定义删除功能?

c++ - 为什么需要 std::minmax_element?

c++ - 检查所有数组成员是否具有相同的值

c++ - 将 `this` 传递给子对象

c++ - std::disjunction 在标准库中的实现