gpt4 book ai didi

c++ - 使用 C++ 更新只读对象的 map

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:00 25 4
gpt4 key购买 nike

void value_multi(const map<string, double>& myMap, string target,double alva) {

double res = 0;
map<string, double>::const_iterator iter = myMap.begin();
for(; iter!=myMap.end(); ++iter) {
string key = iter->first;
vector<string> strs;
boost::split(strs,key, boost::is_any_of("|"));

if(strs[0] == target) { //if target == string value
//res += iter->second;
double tmp=iter->second*alva; // set tmp
iter->second=tmp; //update value
}
}

//return res;
}

我想使用代码之类的方法更新一个值,但编译后显示一些消息

[Error] assignment of member 'std::pair<const std::basic_string<char>, double>::second' in read-only object

是否有任何简单快捷的方法来更改我的代码,从而轻松更新 iter->second

最佳答案

您应该使用“正常”iterator而不是 const_iterator ,因为后者是只读的:

map<string, double>::iterator iter = myMap.begin();

参见: what is the difference between const_iterator and iterator?

注意您还必须更改参数类型 const map<string, double>& myMap将您的函数转换为非 const 类型:

void value_multi(map<string, double>& myMap, string target,double alva)

关于c++ - 使用 C++ 更新只读对象的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33653332/

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