What type do vector strings deduce to?

Viewed 82

I'm becoming familiar with using vectors (reading An introduction to std::vector), and it displays the following code as an example:

// 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>

If I use this C++17 style vector initialization with string literals, what type will the vector deduce (i.e. std::string, char*, etc)?

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

(i.e. std::string

No, string literals are not related to the class std::string. Technically this could happen if vector had a special deduction guide for this, but it doesn't.

... char*

No, string literals are const.

The contained type will be deduced as const char*.

Just wanted to add that the string literals have type const char[N], where N is the number of characters including the terminator, and the vector's list-initializer constructor takes values and not references, thus the literals decay to the pointers const char*.

If you want a vector of std::strings, you can use literal operator ""s:

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

is the same as

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