Cuong Bui
Cuong Bui

Reputation: 19

Vector type String but when initialize with integer

I have below code:

vector<string> v6{10};
cout << v6.size() << endl;
for (int i = 0; i < 10; i++){
    cout << v6[i] << endl;      
}

Output is in the below picture: http://i.prntscr.com/5f8e1fecbdd34fbc9c9d18b9e7e7a2a2.png

Why they print 10 for v6's size. I thought it creates a vector string with the first element is integer. And when I print all value it show something like space

Upvotes: 0

Views: 66

Answers (1)

cdhowie
cdhowie

Reputation: 168988

v6.size() is the size of the vector. You have created a vector of 10 empty strings. If you look at v6[0].size(), for example, it will be zero.

You probably meant to do this:

vector<string> v6{ "10" };

By using an integer instead of a string literal, you called the vector constructor overload that means "create a vector of this many default-constructed elements," where you likely meant "create a vector with these specific elements."

Upvotes: 5

Related Questions