Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently implement assign a vector's data to a number of variables?

For example

void assign(vector<int> const& v, int a, float b)
{
    a = v[0];
    b = (float)v[1];
}

Here the value types doesn't need to be same. I want to make a function to assign variable number of variables. I can use variadic function. But I think using parameter pack may be more efficient. How to implement it? Thanks!

like image 876
user1899020 Avatar asked Dec 16 '25 19:12

user1899020


1 Answers

Fold expressions to the rescue!

template <typename ...P> void assign(const std::vector<int> &v, P &... params)
{
    std::size_t index = 0;
    (void(params = static_cast<P>(v[index++])) , ...);
}

If if has to be in C++11, you could use the dummy array trick:

template <typename ...P> void assign(const std::vector<int> &v, P &... params)
{
    std::size_t index = 0;
    using dummy = int[];
    (void)dummy{0, (void(params = static_cast<P>(v[index++])), 0) ...};
}
like image 148
HolyBlackCat Avatar answered Dec 19 '25 12:12

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!