Return Ordering Without a vector

天涯浪子 提交于 2019-12-31 05:07:10

问题


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]);
    }
 }

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))

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]);

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?


回答1:


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); };
} 

Could be called like this:

vertex_triangle(i, bar)(foo)

Live Example



来源:https://stackoverflow.com/questions/47083657/return-ordering-without-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!