Reputation: 387
I have a vector of strings, and I fill the first string in it manually character by character
vector <std::string> vec(6);
vec[0][0] = 'h';
vec[0][1] = 'e';
vec[0][2] = 'y';
cout << "vec[0] = " << vec[0] << "\n"
now I want to print the vec[0] which is supposed to be a string "hey"
, but it prints empty space.
I can print only if I print it character by character also, like this
for(int i = 0 ; i<1 ; i++)
{
for(int j = 0 ; j < 3 ; j++)
{
cout << vec[i][j];
}
cout << "\n";
}
Why I can't simply print the string as a whole.
Upvotes: 0
Views: 66
Reputation: 4863
vector <std::string> vec(6);
gives you a vector of six empty strings. vec[0][0] = 'h';
is trying to assign the character h
into the first slot of the first empty string, which is not legal, as the bracket operator can only replace existing characters. Use something like vec[0] += 'h'
to append to the string.
Upvotes: 2