2d char vector printing spaces when printing second column

故事扮演 提交于 2020-07-22 06:00:10

问题


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 chars, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!