C++带有初始值设定项的新 if 语句

C++ new if statement with initializer

本文关键字:if 语句 C++      更新时间:2023-10-16

"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::mapiterator将被取消引用为 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(); }