Hariom Singh
Hariom Singh

Reputation: 3632

Using fold expression to merge multiple vector

Trying to learn some of the new features of c++17 came across fold expression. http://en.cppreference.com/w/cpp/language/fold

Using the fold expression I am able to do multiple push_back of elements .I was just trying to use the fold expression to merge multiple vector into a single vector .I know there are other ways to do merge the vector , but want to do it using fold expression

#include <iostream>
#include <vector>

template<typename T, typename... Args>
void push_back_vec(std::vector<T>& v, Args&&... args)
{
    (v.push_back(args), ...);
}
int main()
{

    std::vector<int> v;
    std::vector<int> m ={1,2,3};
    std::vector<int> x ={4,5,6};
    std::vector<int> y ={7,8,9};

    //push_back_vec(v,m,x,y);

    push_back_vec(v, 66, 67, 68);
    for (int i : v) std::cout << i << ' ';

}

Any suggestion will be helpful

Output

66 67 68 Program ended with exit code: 0

Trying to make below statement working which adds m,x,y vectors to v

 push_back_vec(v,m,x,y);

Presently getting error for below line "No matching argument" //which is expected

push_back_vec(v,m,x,y);

what needs to be changed here

void push_back_vec(std::vector<T>& v, Args&&... args)

Upvotes: 0

Views: 2471

Answers (1)

Jarod42
Jarod42

Reputation: 218118

To concatenate 2 vectors, you may do

template <typename T>
void concatenate(std::vector<T>& v, const std::vector<T>& v2)
{
    v.insert(v.end(), v2.begin(), v2.end());
}

so to concatenate N vectors, you may do

template <typename T, typename ... Ts>
void concatenate(std::vector<T>& v, const Ts&... ts)
{
    (v.insert(v.end(), ts.begin(), ts.end()), ...);
}

If you want the same function to append value or vector, you may add several overloads:

template <typename T>
void append(std::vector<T>& v, const std::vector<T>& v2)
{
    v.insert(v.end(), v2.begin(), v2.end());
}

template <typename T>
void append(std::vector<T>& v, const T& value)
{
    v.push_back(value);
}

and then

template<typename T, typename... Args>
void push_back_vec(std::vector<T>& v, Args&&... args)
{
    (append(v, args), ...);
}

Demo

Upvotes: 9

Related Questions