c++ - 将字符串分配给 char 数组的列

标签 c++ string multidimensional-array char

我正在尝试将“hello”之类的字符串分配给 C++ 中的多维字符数组的一列。例如,完成后,二维数组的第一列应从上到下变为“hello”。

我正在寻找一种不使用 for 循环的简单解决方案,例如使用 strcpy()。这可能吗?

最佳答案

我强烈建议不要使用 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,这实际上非常简洁,并且肯定有助于隐藏使用 2-dim 数组的所有困惑在 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";
}

关于c++ - 将字符串分配给 char 数组的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044783/

相关文章:

java - 字符串按点分割 - Java

javascript - 多维数组的长度 - 无法读取 null 的属性 'length'

c++ - 有没有办法使用预先存在的对象作为 C++ 中第一个对象的子对象来创建对象?

c++ - 为什么 Visual Studio 在这种情况下不执行返回值优化 (RVO)

php - 如何删除 "matching"括号之间的文本?

Java 格式化行以使列对齐

c++ - C++ 函数定义中的 "Type&"与 "Type*"

c++ - 将 std::vector<std::string> 转换为 const char* const*

带有命名和编号索引的 Javascript 多维对象

java - 在构造时选择性地为多维数组分配维度