简体   繁体   中英

How can I write a function in C++ that takes variable number of vectors of double?

I am trying to combine different number of vector<double> variables into a vector< vector<double> > . I try to use cstdarg library. It throws out

error: cannot receive objects of non-trivially-copyable type 'class myvectortype' through '...';

where

typedef vector< double > myvectortype; typedef vector< myvectortype > datavectortype;

Here is the definition of the function

datavectortype ExtractData::GetPixelData(int num, ...)
{
        datavectortype data_temp;
        va_list arguments;
        va_start (arguments, num);
        for(int i = 0; i<num; i++)
        {
                data_temp.push_back(va_arg ( arguments, myvectortype));
        }
        va_end ( arguments );
        return data_temp;
}

What could be done to fix this, thanks.

Since C++11, you already just could do

std::vector<double> v1{1}, v2{2}, v3{3, 4};
std::vector<std::vector<double>> v {v1, v2, v3};

But if you want to do a function for that, you may use variadic template:

template <typename T, typename ...Ts>
std::vector<T> make_vector(const T& arg, const Ts&... args)
{
    return {arg, args...};
}

and so use it like:

std::vector<double> v1{1}, v2{2}, v3{3, 4};
std::vector<std::vector<double>> v = make_vector(v1, v2, v3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM