Humam Helfawi
Humam Helfawi

Reputation: 20264

Merge vector of vectors into a single vector

I have vector of vectors of T:

std::vector<std::vector<T>> vector_of_vectors_of_T;

I want to merge all of them into single vector of T:

std::vector<T> vector_of_T;

I am currently using this method:

size_t total_size{ 0 };
for (auto const& items: vector_of_vectors_of_T){
    total_size += items.size();
}
vector_of_T.reserve(total_size);
for (auto const& items: vector_of_vectors_of_T){
    vector_of_T.insert(end(vector_of_T), begin(items), end(items));
}

Is there more straightforward method? Like a ready std function? If not, is there more efficient way to do it manually?

Upvotes: 24

Views: 4546

Answers (3)

Piotr Smaroń
Piotr Smaroń

Reputation: 446

I guess you could try std::merge/std::move used in a loop - that are already existing std algorithms. Don't know if that's faster.

Upvotes: 2

Praveen
Praveen

Reputation: 9335

Using back_inserter and move;

size_t total_size{ 0 };
for (auto const& items: vector_of_vectors_of_T){
    total_size += items.size();
}

vector_of_T.reserve(total_size);
for (auto& items: vector_of_vectors_of_T){    
    std::move(items.begin(), items.end(), std::back_inserter(vector_of_T));
}

Instead of copying, std::move gives it a bit performance enhancement.

Upvotes: 10

TemplateRex
TemplateRex

Reputation: 70526

It's a nice exercise to try and write up a generic join. The code below takes a nested container R1<R2<T> and returns a joined container R1<T>. Note that because of the allocator parameters in the Standard Library, this is a bit cumbersome. No attempt is being made to check for allocator compatibility etc.

Fortunately, there's action::join function in the upcoming range-v3 library by Eric Niebler, that is quite robust already and works today on Clang:

#include <range/v3/all.hpp>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

// quick prototype
template<template<class, class...> class R1, template<class, class...> class R2, class T, class... A1, class... A2>
auto join(R1<R2<T, A2...>, A1...> const& outer)
{
    R1<T, A2...> joined;
    joined.reserve(std::accumulate(outer.begin(), outer.end(), std::size_t{}, [](auto size, auto const& inner) {
        return size + inner.size();
    }));
    for (auto const& inner : outer)
        joined.insert(joined.end(), inner.begin(), inner.end());
    return joined;
}

int main()
{
    std::vector<std::vector<int>> v = { { 1, 2 }, { 3, 4 } };

    // quick prototype
    std::vector<int> w = join(v);
    std::copy(w.begin(), w.end(), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";

    // Eric Niebler's range-v3
    std::vector<int> u = ranges::action::join(v);
    std::copy(u.begin(), u.end(), std::ostream_iterator<int>(std::cout, ",")); std::cout << "\n";
}

Live Example

Upvotes: 10

Related Questions