访问映射的值(如果其键存在C++

Access map's value if its key exists C++

本文关键字:存在 C++ 如果 映射 访问      更新时间:2023-10-16

只要某个键存在,我就试图访问该键上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;