Return order without vector

So, I call a helper function vertex_triangle, which allows me to pick vector<pair<T, T>>and direct them into ordered triangles, and then put them vectorin that order. I use this as a 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 helper wrapping function is as follows:

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

Initially, I directly put return in vector<Triangle<T>> foo, as it all made sense:

foo.push_back(vertex_triangle(i, bar))

Now I need to use vector<pair<T, T>> foo, so I have to unpack the return 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 to move the vertices from barto foowithout returning a copy of the points, unpacking them and pushing them back one by one?

0
1

out . , . , :

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)

Live Example

0

Source: https://habr.com/ru/post/1688813/


All Articles