C++带有初始值设定项的新 if 语句
C++ new if statement with initializer
"if"语句的cpp首选项页面;
https://en.cppreference.com/w/cpp/language/if
给出以下示例;
除了由 init-语句声明的名称(如果 init-语句是声明)和由条件声明的名称(如果条件是声明)在同一个作用域中,这也是两个语句的作用域 块引用
std::map<int, std::string> m;
if (auto it = m.find(10); it != m.end()) { return it->size(); }
这是一个错字,不是吗?我在这里没有错过任何东西,应该是;
it->second.size();
或
it->first;
不?
是的,这是一个错字。 std::map
的iterator
将被取消引用为 std::map::value_type
,其中 value_type
std::pair<const Key, T>
。
请参阅std::map::find
的用法示例(来自 cpp首选项):
#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 foundn";
}
}
你是对的。给定的代码无法编译。看这里。编译器错误为:
error: 'struct std::pair<const int, std::__cxx11::basic_string<char> >' has no member named 'size'
std::pair
没有size
成员。但std::string
拥有它。
所以正确的代码应该是:
if (auto it = m.find(10); it != m.end()) { return it->second.size(); }
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复