gpt4 book ai didi

c++ - const map & 作为函数参数

转载 作者:行者123 更新时间:2023-11-28 00:13:12 25 4
gpt4 key购买 nike

我正在尝试使用随机值填充 map 的函数,但出现此错误:

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

我该如何理解?

最佳答案

如果你试图insertmap,它肯定不能是const。插入是一种变异操作。将签名改为

void mapInit(map<int,char>& mp)

关于c++ - const map & 作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com