访问映射的值(如果其键存在C++
Access map's value if its key exists C++
只要某个键存在,我就试图访问该键上map的值。
要检查密钥是否存在,我有:
if (pos.find(test[i]) != pos.end())
在if语句内部,我希望将我的计数器按如下方式递增:
posProb *= pos[test[i]]->second;
整个功能设置如下:
void compute(vector<string> test, map<string, double> pos, map<string, double> neg) {
double posProb = 1, negProb = 1;
for (int i = 0; i < test.size(); i++) {
if (pos.find(test[i]) != pos.end())
posProb *= pos[test[i]]->second * UNDERFLOWVAR;
else posProb *= pos.find("UNK")->second * UNDERFLOWVAR;
}
cout << posProb;
如何调整我当前拥有的内容,以便适当地访问映射的第二个变量(值)?
这样的东西怎么样?
auto unk = pos["UNK"];
for (int i = 0; i < test.size(); i++) {
auto it = pos.find(test[i]);
posProb *= (it != pos.end() ? it->second : unk) * UNDERFLOWVAR;
}
您的find
已经失败,所以您可能想要以下内容:
void compute(vector<string> test, map<string, double> pos, map<string, double> neg) {
double posProb = 0, negProb = 0;
for (int i = 0; i < test.size(); i++) {
if (pos.find(test[i]) != pos.end()) {
posProb *= pos[test[i]]->second * UNDERFLOWVAR;
{
else {
if (pos.find("UNK") == pos.end()) {
pos("UNK") = 1; //??
}
posProb *= pos.find("UNK")->second * UNDERFLOWVAR;
}
}
cout << posProb;
相关文章:
- C++模板来检查友元函数的存在
- 既然存在危险,为什么项目要使用-I include开关
- 我们可以访问一个不存在的联盟的成员吗
- C++:对不存在的命名空间使用命名空间指令
- C++quit()函数中可能存在作用域问题
- C++擦除(如果存在)
- g++ 说函数不存在,即使包含正确的标头
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 有了gcc,是否可以链接库,但前提是它存在
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- C++Builder中的OnClick事件签名存在问题
- 如何正确地将分支添加到已存在的树中
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 如何检查QList中是否存在值
- 根据某个函数是否存在启用模板
- 如何将分支添加到已存在的TTree:ROOT
- 地图计数确实很重要,或者只是检查是否存在
- 通用C++/Python 多语言的存在
- 为什么我的共享库中存在展开符号