const map&作为函数参数

时间:2015-08-11 19:35:35

标签: c++ dictionary stl

我正在尝试使用随机值来填充地图,但是我收到了这个错误:

 passing 'const std::map<int,char>' as 'this' argument of
 'std::pair<typename std::_Rb_tree<_Key, std::pair<const_Key,_Tp>, etc.

功能:

void mapInit(const map<int,char> &mp)
{
   for (int i = 0; i < 10; i++)
   {
      int x = rand() % 100;
      char c = 'a' + rand() % 10;
      pair<int,char> p;
      p = make_pair(x,c);

      mp.insert(p);
   }
}

我该如何理解这一点?

2 个答案:

答案 0 :(得分:3)

如果您尝试floor()进入insert,则肯定不能map。插入是一种变异操作。将签名更改为

const

答案 1 :(得分:0)

首先,如果要将元素插入到地图中,则不能使用const。 其次,你应该使用例如uniform_int_distribution而不是c-style rand()。

示例:

class rand_int
{
public:
    rand_int(int l, int h) : p{l, h} {};
    int operator()() const {return r();}
private:
    uniform_int_distribution<>::param_type p;
    function<int()> r = bind(uniform_int_distribution<>{p}, default_random_engine{});
};
相关问题