简体   繁体   English

如果键不存在,我可以从std :: map获取一个值而不会崩溃吗?

[英]Can I get a value from std::map without crashing if the key doesn't exist?

I have C++ code like this: 我有这样的C ++代码:

if(rtstructure.find(varName) != rtstructure.end()) {
    rtdef = rtstructure[varName];
}

where rtstructure is std::map with std::string for the key. 其中rtstructure是std :: map,键为std :: string。 This code works but it seems like a waste to make it search twice for the same key. 这段代码有效,但是让它两次搜索同一密钥似乎很浪费。 If I omit the if case around the assignment, the program crashes if varName points to a key that doesn't exist. 如果我忽略分配的if大小写,则如果varName指向不存在的键,则程序将崩溃。

Can I in a single map operation look up a key in a std::map and get its value if it exists, without crashing if it doesn't exist? 我可以在单个map操作中查找std :: map中的键并获取其值(如果存在),而如果不存在则崩溃吗?

find give you a std::map<>::iterator that holds/point to std::pair<> . find给你一个std::map<>::iterator ,持有/指向std::pair<> The iterator can be saved and reused (given that you did not do anything to invalidate it such as erase ). 可以保存并重复使用迭代器(前提是您没有做任何事情来使它无效,例如erase )。

// i don't know the type of rtstructure so i use auto
// you can replace it to the correct type if C++11 is not available
auto it = rtstructure.find(varName); 
if(it != rtstructure.end()) {
    rtdef = it->second;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM