3

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?

13
  • 3
    what type should it deduce? You are aware that some of the literals are of different type? Commented Oct 30, 2019 at 13:08
  • 6
    Do you know what the type of a string literal is? Commented Oct 30, 2019 at 13:08
  • I think the issue is clearer with integer values. The compiler would not know which integer type to use. Commented Oct 30, 2019 at 13:15
  • @formerlyknownas_463035818 Well, aren't "some","test,"cases" are of std::string type? I write std::string x = "Hello" and it works without any issue. What am I missing here? Commented Oct 30, 2019 at 13:15
  • 1
    @UtkarshGupta std::string myStr = "sampletext" you declare type, can't be ambiguous or something else. I suppose it passes a C-string to std::string constructor and then builds an std::string - but I am not sure about this. Commented Oct 30, 2019 at 13:31

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that std::string user defined literals are only available from c++ 14 (which is fine here given OP's C++17 tag, but good to note for future readers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.