【问题标题】:C++ new if statement with initializer带有初始化程序的 C++ 新 if 语句
【发布时间】:2019-05-30 22:33:22
【问题描述】:

“if”语句的 cppreference 页面;

https://en.cppreference.com/w/cpp/language/if

给出下面的例子;

除了init-statement声明的名字(如果init-statement是一个声明)和condition声明的名字(如果condition是一个声明)在同一个作用域,这也是两个语句的作用域 块引用

std::map<int, std::string> m;
if (auto it = m.find(10); it != m.end()) { return it->size(); }

这是一个错字,不是吗?我没有错过任何东西,我应该是;

it->second.size(); 

it->first;

没有?

【问题讨论】:

  • 好收获。幸运的是,cppreference.com 是一个 wiki,所以你可以自己解决这个问题。
  • 感谢@aschlper,我修复了相关页面。

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


【解决方案1】:

是的,这是一个错字。用于std::mapiterator 将被取消引用为std::map::value_type,其中value_typestd::pair&lt;const Key, T&gt;

查看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";
    }
}

【讨论】:

    【解决方案2】:

    你是对的。给出的代码无法编译。见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(); }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多