This post will discuss how to flatten a vector of vectors in C++.

1. Using std::insert function

A simple solution is to iterate over the vector of vectors and insert the contents of each vector into a new vector using the std::insert function. It is overloaded to accept a range of elements to insert at the specified position, in the same order. A typical implementation of this approach would look like this:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9

2. Using Nested Loop

Another option to flatten a nested vector is using the nested for loop. The idea is to pick every element using a nested for-loop and push add it at the end of a new vector. Here’s what the code would look like:

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9

3. Using std::accumulate

Another option to flatten a vector of vectors is using the standard function std::accumulate, defined in the header <numeric>. We can overwrite its default operation by providing a binary predicate in the optional fourth parameter, which performs the flatten operation on two vectors and return the flattened list.

Download  Run Code

Output:

1 2 3 4 5 6 7 8 9

4. Using range-v3 library

Here’s a one-liner using the ranges::views::join function from ranges-v3 library, which forms the basis for C++20’s std::ranges.

Download Code

Output:

1 2 3 4 5 6 7 8 9

That’s all about flattening a vector of vectors in C++.