“if”语句的 cppreference 页面;
https://en.cppreference.com/w/cpp/language/if
给出了下面的例子;
Except that names declared by the init-statement (if init-statement is a declaration) and names declared by condition (if condition is a declaration) are in the same scope, which is also the scope of both statements Blockquote
std::map<int, std::string> m;
if (auto it = m.find(10); it != m.end()) { return it->size(); }
这是一个错字,不是吗?我没有遗漏任何东西,我应该遗漏任何东西;
it->second.size();
或
it->first;
没有?
最佳答案
是的,这是一个错字。 iterator
对于 std::map
将被取消引用为 std::map::value_type
, 其中value_type
是std::pair<const Key, T>
.
参见 std::map::find
的用法示例(来自 cppreference):
#include <iostream>
#include <map>
int main()
{
std::map<int,char> example = {{1,'a'},{2,'b'}};
auto search = example.find(2);
if (search != example.end()) {
std::cout << "Found " << search->first << " " << search->second << '\n';
} else {
std::cout << "Not found\n";
}
}
关于C++ 新的带有初始化器的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54037489/