Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a string literal initializer list for a std::vector create a std::vector<std::string> in C++?

In C++, if I do:

std::vector words {"some","test","cases","here"};
  • Can anyone explain why words is not a std::vector<std::string> type of container?

  • Isn't C++ supposed to deduct the type through the initializer-list I gave?

  • If "some", "test" are not string literals, what do std::string literals look like?

like image 682
MrProgrammer Avatar asked Apr 22 '26 15:04

MrProgrammer


1 Answers

a string literal, like "something", is a c-string. It creates a const char[N] with static storage duration where N is the number of characters plus a null terminator. That means when you do

std::vector words {"some","test","cases","here"};

What you've done is create a std::vector<const char*> since arrays can decay to pointers.

If you want a std::vector<std::string> then what you need is to use the std::string user defined literal. That would look like

using namespace std::string_literals;
std::vector words {"some"s,"test"s,"cases"s,"here"s};

and now you have actually std::strings that the compiler will use to deduce the type of the vector.

like image 53
NathanOliver Avatar answered Apr 24 '26 06:04

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!