C++ 新的带有初始化器的 if 语句

标签 c++ if-statement c++17 initializer

“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_typestd::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/

相关文章:

c++ - 计算可变参数模板元组中的 std::optional 类型

c++ - 在 C++ 中限制对类的公共(public)成员的访问的设计模式

c++ - 存储稍后转发的变量参数

c++ - C++ 中的类析构函数内存处理

C++ 2011 std::regex 根本不起作用

c++ - Google Protocol Buffer ,如何设置自定义类型的字段?

c++ - Linux g++ new (std::nothrow) 确实有效

javascript - jQuery if/else 语句不起作用

java - Java 初学者(循环)- 缺少 return 语句

java - 最大值未返回正确值