gpt4 book ai didi

c++ - STL 对的默认构造值

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:51 28 4
gpt4 key购买 nike

我正在尝试让以下 map 正常工作:

enum ttype { shift, reduce }
map <string, pair<ttype, int> > lookup;

所以这工作正常,但我需要一种方法来检查是否找不到 key 。因此,例如,效果如下:

cout << (lookup["a"]==NULL) << endl; // this is wrong, but I am trying to find a way to identify when lookup["a"] does not find a corresponding value

似乎如果找不到键,map 将返回默认的构造值(例如,如果它映射到一个字符串,它只会返回空字符串,我可以只检查 lookup["a"] == ""- 但我不知道 std::pairs 的默认构造值是什么)。

最佳答案

operator[] 在找不到项目时添加该项目并返回默认构造的项目。 find() 不返回默认构造的对,而是返回指向 map 最后一个值之外的迭代器。

auto iter = lookup.find("a");
if (iter != lookup.end()) {
std::cout << "Key was found :)" << std::endl;
std::pair<ttype, int> result = iter->second;
std::cout << "Result was: " << result.second << std::endl;
} else {
std::cout << "Key was not found" << std::endl;
// Maybe add the key to the map?
}

使用 find() 有点冗长,但它使它更具可读性(在我看来)。

关于c++ - STL 对的默认构造值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337865/

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