没有向量的退货排序 [英] Return Ordering Without a vector
问题描述
所以我调用了一个辅助函数,vertex_triangle
,它允许我接收一个 vector
并缠绕它们成有序的三角形,然后按顺序将它们放在 vector
中.我使用它作为我的返回对象:
So I am calling a helper function, vertex_triangle
, quite a bit to allow me to take in a vector<pair<T, T>>
and wind them into ordered triangles, then put those in a vector
in that order. I'm using this as my return object:
template <Typename T>
struct Triangle {
Triangle(const pair<T, T>& first, const pair<T, T>& second, const pair<T, T>& third) {
data[0] = first;
data[1] = second;
data[2] = third;
}
pair<T, T> data[3];
};
所以我的绕组辅助函数看起来像这样:
So my winding helper function looks like this:
template<typename T>
triangle<T> vertex_triangle(const size_t index, const
vector<pair<T, T>>& polygon){
if (0 == index){
return Triangle(polygon.back(), polygon.front(), polygon[1]);
}else if (index == (polygon.size() - 1)){
return Triangle(polygon[polygon.size() - 2], polygon.back(), polygon.front());
}else{
return Triangle(polygon[index - 1], polygon[index], polygon[index + 1]);
}
}
最初我是直接将返回值放在 vector
这样都说得通:
Originally I was directly placing the return in a vector<Triangle<T>> foo
like this all made sense:
foo.push_back(vertex_triangle(i, bar))
现在我需要使用 vector
所以我必须解压 vertex_triangle
的返回:
Now I need to use a vector<pair<T, T>> foo
so I'd have to unpack the return of vertex_triangle
:
const auto temp = vertex_triangle(i, bar);
foo.push_back(temp[0]);
foo.push_back(temp[1]);
foo.push_back(temp[2]);
但我真的不喜欢临时对象,有没有办法以某种方式返回我想要将顶点从 bar
推入 foo
的顺序而不返回一个点的副本,拆包,一一推回去?
But I don't really like the temporary object, is there a way to somehow return the order that I want push the verts from bar
into foo
without returning a copy of the points, unpacking them, and pushing them back one by one?
推荐答案
所以 您的评论使用 out 参数 是这里最直接的选项.另一种选择是返回一个 lambda,它将通过引用捕获您的输入.例如:
So your comment on using an out parameter is the most direct option here. The other alternative would be to return a lambda, which would capture your inputs by reference. So for example:
template <typename T>
auto vertex_triangle(const size_t index, const vector<pair<T, T>>& polygon) {
const auto& first = index == 0U ? polygon.back() : polygon[index - 1U];
const auto& second = polygon[index];
const auto& third = index == size(polygon) - 1U ? polygon.front() : polygon[index + 1U];
return [&](auto& output){ output.push_back(first);
output.push_back(second);
output.push_back(third); };
}
可以这样称呼:
vertex_triangle(i, bar)(foo)
这篇关于没有向量的退货排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!