打印第二列时的二维字符向量打印空间 [英] 2d char vector printing spaces when printing second column

查看:33
本文介绍了打印第二列时的二维字符向量打印空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有一个二维字符向量 -

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.

推荐答案

在您的第一个示例中,对于 solution 的每个元素,您正在尝试构造一个 vector 来自 2 个字符串文字.这将使用带有 2 个迭代器的 vector 构造函数(因为字符串文字可以转换为指针).由于指针未表示有效范围,因此会调用未定义行为 (UB).

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).

在第二个示例中,对于 solution 的每个元素,您尝试从 2 个 char 构建一个 vector,这非常好,并为您提供预期的结果.

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.

这篇关于打印第二列时的二维字符向量打印空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆