我强烈建议不要使用 C++ 中的原始多维数组 - 它们容易出错且不灵活。考虑 Boost MultiArray。
也就是说,您始终可以通过编写辅助函数来“隐藏”复杂性。这是一个相当通用的版本,适用于任何大小/元素类型的二维数组:
template<typename T, size_t N, size_t M>
void setColumn(T(&arr)[N][M], size_t col, std::string const& val)
{
assert(col>=0 && col <M);
for (auto& row : arr)
row[col] = val;
}
注意它是怎么回事
- 通过引用获取数组,因此模板参数推导可用于“感知”维度边界(N,M)
- 它断言列索引实际上是有效的(奖励功能)
- 它使用基于范围的
for,这实际上非常简洁,并且肯定有助于隐藏在 C++ 中使用二维数组会暴露的所有混乱你去。
如何使用?
std::string arr[][7] = {
{ "0", "1", "2", "3", "4", "5", "6" },
{ "0", "1", "2", "3", "4", "5", "6" },
{ "0", "1", "2", "3", "4", "5", "6" },
{ "0", "1", "2", "3", "4", "5", "6" },
{ "0", "1", "2", "3", "4", "5", "6" },
{ "0", "1", "2", "3", "4", "5", "6" },
};
// straightforward:
setColumn(arr, 0, "hello");
或者,如果您不想“说出”哪个数组,请使用 lambda:
// to make it even more concise
auto setColumn = [&](int c, std::string const& val) mutable { ::setColumn(arr, c, val); };
setColumn(3, "world");
现场演示是Here on Coliru,它会打印出来
hello;1;2;world;4;5;6;
hello;1;2;world;4;5;6;
hello;1;2;world;4;5;6;
hello;1;2;world;4;5;6;
hello;1;2;world;4;5;6;
hello;1;2;world;4;5;6;
使用简单的代码
// dump it for demo purposes
for (auto& row : arr)
{
std::copy(begin(row), end(row), std::ostream_iterator<std::string>(std::cout, ";"));
std::cout << "\n";
}