【问题标题】:What type do vector strings deduce to?向量字符串推导出什么类型?
【发布时间】:2021-03-13 03:07:24
【问题描述】:

我开始熟悉使用向量(阅读An introduction to std::vector),它显示以下代码作为示例:

// as with std::array, the type can be omitted since C++17
std::vector array4 { 9, 7, 5, 3, 1 }; // deduced to std::vector<int>

如果我将这种 C++17 样式的向量初始化与字符串文字一起使用,向量将推导出什么类型(即std::stringchar* 等)?

std::vector strArray {"Hello", "world", "!!!"};

【问题讨论】:

    标签: c++ string vector type-deduction


    【解决方案1】:

    (即 std::string

    不,字符串文字与std::string 类无关。从技术上讲,如果 vector 对此有特殊的推导指南,则可能会发生这种情况,但事实并非如此。

    ...字符*

    不,字符串字面量是 const。

    包含的类型将被推导出为const char*

    【讨论】:

      【解决方案2】:

      只是想补充一点,字符串字面量的类型为const char[N],其中 N 是包括终止符在内的字符数,并且向量的列表初始化器构造函数采用值而不是引用,因此字面量会衰减到指针 @987654322 @。

      如果你想要一个 std::strings 的向量,你可以使用文字 operator ""s:

      std::vector strArray {"Hello"s, "world"s, "!!!"s};
      

      相同
      std::vector<std::string> strArray {"Hello", "world", "!!!"};
      

      【讨论】:

        猜你喜欢
        • 2011-01-27
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        • 1970-01-01
        • 2011-06-28
        • 2012-02-15
        相关资源
        最近更新 更多