我是c++的新手。我不明白为什么下面的代码打印"r"字符串。我认为它应该是一个 2X3X4 元素的数组,所以通过指向arr[0][0][0]
,我期望第一个 arr= a
的第一个字符串中的第一个字符,但这打印abcd
.谁能解释一下?
#include <iostream>
using namespace std;
int main()
{
string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
cout<<arr [1] [0] [1] [1]<<endl;
return 0;
}
编辑:
让我感到困惑的是python中的行为。以下 python 代码打印a
:
arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]
print arr[0][0][0]
它寻址到第一个列表中第一个字符串的第一个字母。
我认为在 c++ 中等效的是:
#include <iostream>
using namespace std;
int main()
{
string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
cout<<arr[0][0][0]<<endl;
return 0;
}
通过指向第一个数组的第一个字符串中的第一个字母。但这打印了第一个字符串abcd
.我的问题是我为什么要再放一个[0]
才能到达a
?
初始值设定项按如下方式填充数组:
arr[0][0][0] = "abcd";
arr[0][0][1] = "efgh";
arr[0][0][2] = "ijkl";
arr[1][0][0] = "mnop";
arr[1][0][1] = "qrst";
arr[1][0][2] = "xywz";
所有其他元素默认初始化为空字符串。
因此,arr[1][0][1]
是包含"qrst"
的字符串,arr[1][0][1][1]
是该字符串的第二个字符,即'r'
。
您将标准库string
对象与 c 字符串/字符串文本的概念混淆了,并且通过避免使用 std::
前缀来帮助自己解决这个问题。如果我们添加这个,它开始更有意义:
std::string arr [2] [3] [4]={
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
您在这里声明的是一个 2 x 3 x 4 个 std::string 实例的数组。但是你写的东西看起来就像你认为你在声明字符数组:
char arr [2] [3] [4] = {
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
几乎会产生您试图达到的效果 - 在这种情况下arr[0][0][0]
确实指向a
而不是字符串。
不幸的是,这里的问题是你指定了 4 的最终维度,然后向初始值设定项提供了 5 个字符的 c 字符串。记得:
"abcd"
相当于
{ 'a', 'b', 'c', 'd', 0 }
因为 C 字符串是以 NUL 结尾的。所以你需要写
char arr [2] [3] [5] = {
{"abcd","efgh","ijkl"},
{"mnop","qrst","xywz"}
};
或者,如果你真正想要的是特定的字符数组,而不是以 NUL 结尾的 C 字符串:
charr arr[2][3][4] = {
{ { 'a', 'b', 'c', 'd' }, { 'e', 'f', 'g', 'h' }, ...
std::string
是一个离散对象,而不是 c 字符串的别名。
#include <iostream>
#include <string>
int main() {
std::string arr[2][3] = {
{ "abcd", "efgh", "ijkl" },
{ "mnop", "qrst", "wxyz" }, // who needs 'u' or 'v'?
};
std::cout << "arr[0][0] = " << arr[0][0] << "n";
std::cout << "arr[0][0][0] = " << arr[0][0][0] << "n";
}
http://ideone.com/JQrDxr
您初始化的数组可能不是您要初始化的数组。
一维字符串数组
string arr [2]= {"abcd","efgh"};
二维字符串数组
string arr [2][2]= {{"abcd","efgh"}, {"ijkl","mnop"}};
三维字符串数组
string arr [2][2][2]= {
{
{"abcd","qwer"},
{"efgh","tyui"}
},
{
{"ijkl","zxcv"},
{"mnop","bnmo"}
}
};
因此,cout<<arr [1] [0] [1] [1]<<endl;
将输出"x">
你不能将python与c ++进行比较,因为在python中,列表和字符串几乎相同,而在c ++中则完全不同。在Python中,你写并不重要
arr=[["abcd","efgh","ijkl"],["mnop","qrst","xwyz"]]
或
arr=[["a","b","c","d","e","f","g","h","i","j","k","l"],
["m", "n","o","p","q","r","s","t","x","w","y","z"]]
相反,在C ++中,它将字符串视为一个"容器",这会导致您观察到的行为,它将这些"容器"分配给第一个索引而不是单个字符。相反,您可以做的是
char[2][12] arr = {
{"a","b","c","d","e","f","g","h","i","j","k","l"},
{"m", "n","o","p","q","r","s","t","x","w","y","z"}
};