VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-flatten-a-vector-of-vectors-or-2d-vector-in-c/

⇱ How to flatten a Vector of Vectors or 2D Vector in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to flatten a Vector of Vectors or 2D Vector in C++

Last Updated : 12 Jul, 2025

Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples:

Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]] Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]] Output: 1 2 3 4 5 6 8

Algorithm:

  1. 2D Vector can be flattened using iterators.
  2. Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively.
  3. Create a hasNext() method to check if it has the vector has next element or not.
  4. Print the current element, if hasNext() yields true

Below is the implementation of the above approach: 

Output:
1 2 3 4 5 6 7 8 9 10

Time Complexity: O(N)

Auxiliary Space: O(N)

Comment
Article Tags: