【问题标题】:Pushing a variable number of objects into a function using C++?使用 C++ 将可变数量的对象推送到函数中?
【发布时间】:2017-04-24 17:39:34
【问题描述】:

我有多个来自同一个类的对象,我想将它们传递给一个函数。对象只是用于定义运动位置的 8 维“点”,我想将它们传递给一个函数,以将每个对象的部分分离为其他向量(旋转、平移)。

我不知道将每个类对象存储在多维数组中是否更简单,并将其与点数的整数一起传递给函数。我也不太确定该怎么做,所以非常感谢任何帮助!

// Define motion points as 'global' for testing purposes
// Eventually can be read from file
// Defined to match constructor
double v0 = 1;
Point8D M0(v0, 1, 1, 1, 1, 0, 0, 0);                        // First position, no rotation
Point8D M1(v0, 2, 1.5, 1, 1 / sqrt(2), 0, 1 / sqrt(2), 0);  // 90deg about y
Point8D M2(v0, 0, 1.5, 2, 1 / sqrt(2), 0, 1 / sqrt(2), 0);  // Translation, no rotation from 2nd pos
Point8D M3(v0, 2, 3, 1.5, 0, 1 / sqrt(2), 1 / sqrt(2), 0);  // 180 about y, 90 about x
Point8D M4(v0, 3, 2, 3, 1 / sqrt(2), 0, -1 / sqrt(2), 0);   // 270 about y
Point8D M5(v0, 5, 4, 3.5, 1 / sqrt(2), -1 / sqrt(2), 0, 0); // -90 about z
Point8D M6(v0, 8, 5, 5.5, 1, 0, 1 / sqrt(2), -1 / sqrt(2)); // 180 about y, 90 about z
int numPosn = 7;

【问题讨论】:

  • std::vector 点数?
  • 1 / sqrt(2)-1 / sqrt(2) 是常量。无需继续计算它们,只需使用常量即可。
  • @Walter 该函数尚未明确定义,但 Point8D 已如此定义,因为来自用户的输入将按此处所示输入(或从文件中读取)。我需要做的是将不同的数学函数应用于对象的第一个点,然后是对象的第二个点,等等。我计划做的是使用某种形式的函数解析输入,然后使用这些值为八个参数中的每一个定义向量。我无法更改接受输入的方式,但可以更改其他所有内容。
  • 如果函数可以递归定义,您可以使用可变参数模板函数。如果不是,您可以接受单个参数std::initializer_list<Point8D>,可以像your_function({M0, M1, M2, M3...}) 一样调用。
  • @PaulMcKenzie 编译器很可能会优化它。

标签: c++ object vector


【解决方案1】:

您提到您稍后将从文件中读取点。我建议您从文件中将它们读入 Point8D 的标准向量中。然后让你的函数期望一个 Point8D 向量作为它的参数。

【讨论】:

  • 那么简单地定义(1D)向量 motionPosn,并将其传递给函数?这肯定更有意义,现在我正在考虑它,因为点的数量是明确定义的,所以迭代会很简单。
【解决方案2】:

您可以只使用单个 Point8D 的函数,然后使用后者的容器。例如

void split(Point8D const&x, Point3D&rot, Point3D&trans)
{
  /* ... */
}

std::vector<Point8D> P;
/* ... code to fill P */

std::vector<Point3D> R(P.size()), T(P.size());
for(size_t i=0; i!=P.size(); ++i)
  split(T[i], R[i], T[i]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多