I want to combine many vectors to one using a template function with varidic arguments. I have a problem with three or more vectors, below my current code:
#include <iostream>
#include <vector>
#include <numeric>
template<typename _Ty, typename ..._Args>
std::vector<_Ty> combine(const std::vector<_Ty> &a, const _Args &...args) {
// Determine size of new vector
std::vector<std::size_t> sizes = { a.size(), args.size()... };
std::size_t size = std::accumulate(sizes.begin(), sizes.end(), 0);
// Create vector with new size
std::vector<_Ty> result(size);
// Insert all vectors into this one
result.insert(a.begin(), a.end(), result.end());
result.insert(result.end(), args.begin()..., args.end()...);
return result;
}
int main(int argc, char *argv[], char *envp[]) {
std::vector<int> a = { 0, 1, 2, 3, 4 };
std::vector<int> b = { 4, 3, 2, 1, 0 };
std::vector<int> c = { 1, 1, 1, 1 };
std::cout << combine(a, b).size() << std::endl;
std::cout << combine(a, b, c).size() << std::endl; // <-- Does not compile
std::cin.ignore();
return 0;
}
So the exact problem is combine(a, b, c) does not compile. I know why. Because this line:
result.insert(result.end(), args.begin()..., args.end()...);
Get compiled to:
result.insert(result.end(), b.begin(), c.begin(), b.end(), c.end());
But I don´t know how to call result.insert with varidic arguments so it would compiled to:
result.insert(result.end(), b.begin(), b.end());
result.insert(result.end(), c.begin(), c.end());
One possibility would be:
std::vector<std::vector<_Ty> all = { a, args...};
for (const auto &vec : all) {
result.insert(vec.begin(), vec.end());
}
But this would need a second copy of all vectors.... any idea? Thank you!