问题
Here I have a 2d vector of char -
std::vector<std::vector<char>> solution = {
{"O","1"},
{"T","0"},
{"W","9"},
{"E","5"},
{"N","4"}
};
Printing anything from first column - prints fine.
cout << "In main - " << solution [ 1 ] [ 0 ]; // Prints T
But when I try to access element of second column.
cout << "In main - " << solution [ 1 ] [ 1 ]; // Prints blank space - I can't seem to understand why's the case.
After quiet amount of searching I tried by putting single quotes around every element.
std::vector<std::vector<char>> solution = {
{'O','1'},
{'T','0'},
{'W','9'},
{'E','5'},
{'N','4'}
};
It works fine in this case.
cout << "In main - " << solution [ 1 ] [ 1 ]; // Gives me 0 in this case.
Now why is it that I'm getting blank spaces when accessing second column in "" double quotes
scene.
回答1:
In your first example, for each element of solution
, you are trying to construct a vector<char>
from 2 string literals. This will use the constructor of vector
that takes 2 iterators (since string literals can be converted to pointers). Since the pointers are not denoting a valid range, this invokes undefined behavior (UB).
In the second example, for each element of solution
, you are trying to construct a vector<char>
from 2 char
s, which is perfectly fine, and gives you the result you expected.
来源:https://stackoverflow.com/questions/62831470/2d-char-vector-printing-spaces-when-printing-second-column