我在visual C ++中有一个2d字符串数组,如下所示:
static array<System::String ^, 2> ^messages = {
{"a", "b"},
{"c", "d", "e"},
{"f"},
};
我想像这样打印数据:
for(int i = 0; i < 3; i++)
for(int j = 0; j < messages[i]->Length; j++) //ERROR
//print messages[i, j]
我无法获得动态创建的数组的长度。我怎么能这样做?
答案 0 :(得分:3)
你的意图并不完全清楚,但是如果你想为那种(;;)循环工作做出那样的话,你必须创建一个jagged array。一个数组数组,每个元素都是一个数组,而不是它自己的大小。
ref class Test {
static array<array<String^>^>^ messages = {
gcnew array<String^> {"a", "b"},
gcnew array<String^> {"c", "d", "e" },
gcnew array<String^> {"f" }
};
public:
static void Run() {
for (int i = 0; i < messages->Length; i++) {
for (int j = 0; j < messages[i]->Length; j++)
Console::Write("{0} ", messages[i][j]);
Console::WriteLine();
}
}
};
输出:
a b
c d e
f
答案 1 :(得分:2)
array<System::String^, 2>
声明了一个二维数组。以这种方式创建的阵列具有固定的高度和高度。宽度。
array<String^, 2>^ messages =
{
{"a", "b"},
{"c", "d", "e"},
{"f"},
};
Debug::WriteLine("The total number of array elements is {0}", messages->Length);
Debug::WriteLine("Dimension 0 has a length of {0}", messages->GetLength(0));
Debug::WriteLine("Dimension 1 has a length of {0}", messages->GetLength(1));
Debug::WriteLine("{");
for (int i = 0; i < messages->GetLength(0); i++)
{
Debug::Write(" { ");
for (int j = 0; j < messages->GetLength(1); j++)
{
Debug::Write("\"" + messages[i,j] + "\", ");
}
Debug::WriteLine("}");
}
Debug::WriteLine("}");
输出:
The total number of array elements is 9 Dimension 0 has a length of 3 Dimension 1 has a length of 3 { { "a", "b", "", } { "c", "d", "e", } { "f", "", "", } }
但是,根据您初始化数组的方式以及循环方式,看起来您对锯齿状数组感兴趣,而不是常规二维(正方形/矩形) )数组。这应该被声明为一个数组数组:每个内部数组都是单独初始化的,因此每个数组都有自己的长度。
array<array<String^>^>^ messages =
{
{"a", "b"},
{"c", "d", "e"},
{"f"},
};
// The only thing we can tell easily is the number of rows. The total
// number of elements and the column count would require iteration.
Debug::WriteLine("There are {0} rows in the jagged array", messages->Length);
Debug::WriteLine("{");
for (int i = 0; i < messages->Length; i++)
{
Debug::Write(" { ");
for (int j = 0; j < messages[i]->Length; j++)
{
Debug::Write("\"" + messages[i][j] + "\", ");
}
Debug::WriteLine("}");
}
Debug::WriteLine("}");
输出:
There are 3 rows in the jagged array { { "a", "b", } { "c", "d", "e", } { "f", } }