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

C++ new if statement with 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;

没有?

你是对的。给出的代码无法编译。参见 here。 编译器错误是:

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(); }

是的,这是一个错字。 std::mapiterator 将被取消引用为 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";
    }
}