📚

Understanding C++ Vectors and Their Nesting

Sep 12, 2024

C++ Programming Lecture Notes on Vectors

Introduction

  • Discussed previous topics: Vector, Pair, Vector of Pairs
  • Current topic: Nesting of Vectors
    • Nesting: Vector within Vector
    • Two concepts to cover:
      1. Array of Vectors
      2. Vector of Vectors

Array of Vectors

  • Definition: An array that holds vectors.
    • Syntax: vector<data_type> array_name[size];
  • Characteristics:
    • Array has a fixed size.
    • Each element of the array is a vector of a specific type.
    • Example: vector<int> V[5]; (array of 5 integer vectors)

Visualization

  • Visualize as a 2D array:
    • Fixed number of rows (defined by array size).
    • Variable number of columns (each vector can have a different size).
  • Accessing elements:
    • V[i][j] for accessing elements where i is the row (vector index) and j is the element index within that vector.

Example Code for Array of Vectors

  1. Initialization: vector<int> V[3]; // Array of 3 integer vectors
  2. Inserting Elements:
    • Use push_back on individual vectors:
    V[0].push_back(1); V[1].push_back(2); V[2].push_back(3);
  3. Printing Elements:
    • Use nested loops to iterate through the array of vectors:
    for (int i = 0; i < 3; i++) { for (int j = 0; j < V[i].size(); j++) { cout << V[i][j] << " "; } cout << endl; }

Vector of Vectors

  • Definition: A vector that contains other vectors.
    • Syntax: vector<vector<data_type>> vector_name;
  • Characteristics:
    • Both the number of rows and columns are dynamic and not fixed.
    • Example: vector<vector<int>> V;

Example Code for Vector of Vectors

  1. Initialization: vector<vector<int>> V;
  2. Inserting Elements:
    • Directly push back vectors:
    V.push_back({1, 2, 3}); V.push_back({4, 5});
  3. Printing Elements:
    • Use nested loops with dynamic size:
    for (int i = 0; i < V.size(); i++) { for (int j = 0; j < V[i].size(); j++) { cout << V[i][j] << " "; } cout << endl; }

Key Differences Between Array of Vectors and Vector of Vectors

  • Array of Vectors:
    • Fixed size for the array (number of rows).
    • Each row can have a variable number of elements.
  • Vector of Vectors:
    • Both number of rows and number of columns are dynamic.

Conclusion

  • Understanding the difference between array of vectors and vector of vectors is crucial for efficient data management in C++.
  • Next video will cover coding exercises based on these concepts.