Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to concatenate multiple vectors simply?

Tags:

c++

stl

There currently exist ways to concatenate or merge two vectors with one function.

But, it seems that there's no way to concatenate or merge more than three vectors with one function.

For example,

vector<string> a = {"a", "b"};
vector<string> b = {"c", "d"};
vector<string> c = {"e", "f"};
vector<string> d = {"g", "h"};

// newVector has to include {"a", "b", "c", "d", "e", "f", "g", "h"}
vector<string> newVector = function(a, b, c, d);

If there is not, it seems that this can be implemented by using variadic template.

But, I can't imagine how it can be implemented by variadic template.

Are there any solutions?

like image 339
sungjun cho Avatar asked Dec 23 '22 01:12

sungjun cho


1 Answers

If you can use range v3, you can simply do this:

std::vector<std::string> allVec = ranges::view::concat(a, b, c, d);

See demo here.

You can use this with any vector type.

like image 124
P.W Avatar answered Jan 07 '23 20:01

P.W