C++ 将数组复制到指针参数

标签 c++ arrays

各位

我正在用 C++ 编写一个类来计算空间中的点。我将此类设计为独立于应用程序,所以基本上就是我想要的 -

使用输入参数初始化对象 -> 计算值 -> 检索计算的数组

我更喜欢使用类似 C 的数组(而不是 std::array)。我正在编写 getter 函数 -

// The definition of the ctrlpoints array
GLfloat ctrlpoints[4][4][3];

void GlCircle::getControlPoints(GLfloat* controlPoints) {
    std::copy(std::begin(ctrlpoints), std::end(ctrlpoints), std::begin(controlPoints));
}

基本上它应该将所有值从 ctrlpoints 数组复制到 controlPoints 目标数组。当然,编译器不允许我这样做(它不喜欢 std::begin(controlPoints) 的类型)。也许有人可以提出一个想法,我应该如何返回数组的拷贝?也许这个想法可以通过其他方式实现,请告诉我。

提前致谢。

最佳答案

void GlCircle::getControlPoints(GLfloat* controlPoints) {
    std::copy(std::begin(ctrlpoints), std::end(ctrlpoints), std::begin(controlPoints));
}

不起作用,因为 std::begin(ctrlpoints)std::end(ctrlpoints) 可用于迭代 3D 数组的 2D 数组,它不会自动展平 3D 阵列,因此您可以像对待 1D 阵列一样对待它。

您可以使用三个for 循环将数据从成员变量获取到输出参数。

void GlCircle::getControlPoints(GLfloat* controlPoints) {
    int index = 0;
    for ( int i = 0; i < 4; ++i )
    {
       for ( int j = 0; j < 4; ++j )
       {
          for ( int k = 0; k < 3; ++k )
          {
             controlPoints[index++] = ctrlpoints[i][j][k];
          }
       }
    }
}

关于C++ 将数组复制到指针参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28529798/

相关文章:

C++ 从日期字符串解析时区

c++ - acosl 不在 std 命名空间中?

c++ - 子类到基类的转换问题

c++ - Log4cxx 宏不适用于包含空字符的字符串

javascript - 简单的待办事项列表不起作用

arrays - 如何从 Perl 中的数组中获取哈希值?

ruby - 将方法发送到数组中的每个对象

php - 如何选择多维数组中的第一个元素?

c++ - 在 Qt 中,我的类(class)名称应该以 'Q' 开头吗?

arrays - 如何从数组中获取随机元素并将其从那里删除?