Initializing a <string> Vector with Double Curly Braces

Can someone explain the difference in behavior between initialization with double and single curly braces in the example below?

Code # 1:

vector<string> v = {"a", "b"};
string c(v[0] + v[1]);
cout << "c = " << c;
cout << "c.c_str() = " << c.c_str();

Output number 1:

c = ab
c.c_str() = ab

Code # 2:

vector<string> v = {{"a", "b"}};
string c(v[0] + v[1]);
cout << "c = " << c;
cout << "c.c_str() = " << c.c_str();

Output number 2:

c = a\acke Z\ 
c.c_str() = a
+4
source share
1 answer

Implicit conversion of central. What's happening.

  • vector<string> v = {"a", "b"};You initialize the vector by providing a list of initializers with two elements. Two are std::stringinitialized from string literals and then copied to the vector.

  • vector<string> v = {{"a", "b"}}; , . std::string , . undefined.

, . undefined , v[1]. ( std::string) . :

template< class InputIt >
basic_string( InputIt first, InputIt last, 
              const Allocator& alloc = Allocator() );

InputIt char const [2] ( , char const*). , .

+7

Source: https://habr.com/ru/post/1687216/


All Articles