How to Initialize 2D Vectors in C++

Muhammad Husnain Feb 02, 2024
  1. Vectors in C++
  2. Initialize Vectors in C++
  3. Access the Values of a Vector in C++
  4. Initialize 2-Dimensional Vectors in C++
How to Initialize 2D Vectors in C++

This brief programming tutorial is about the use of 2D vectors in C++.

Before jumping into the 2D vectors, we will first see a quick introduction to vectors and their use in C++. Then, we will move on to multi-dimensional vectors and their use.

Vectors in C++

Vectors act exactly like dynamic arrays with an additional feature of automatically resizing themselves on insertion or deletion of an element. Vectors can store homogenous elements (i.e., elements of similar data types).

A vector can resize its container or storage automatically with the additions and deletions.

All the members of a vector are stored in memory. Every next element is adjacent to the previous one so that it can be accessed easily through iterators.

When a new element is added, it is placed at the end, and it takes a different amount of time upon each insertion because it first checks if the memory is available or not. If the memory is unavailable, it first allocates some new memory and then inserts the element in the vector.

On the other hand, removing an element from the last takes a constant amount of time because it doesn’t perform resizing upon each removal.

Initialize Vectors in C++

We have vector library files in the C++ Standard Template Library (STL). Therefore, to use vectors, we need to include the required header file for it, like this:

#include <vector>

To declare a vector, the following syntax is followed:

vector<int> v1;

Please note that we do not need to specify the vectors’ size, as vectors can grow their size dynamically and automatically when required. We can use the initializer list or uniform initialization to initialize the vector.

These two methods are demonstrated in the example below:

vector<int> vec1 = {21, 22, 23, 24, 25};  // initializer list method
vector<int> vec2{21, 22, 23, 24, 25};     // uniform initialization

There is another method to initialize a vector if we want to populate the whole vector with the same value. This is shown below:

vector<int> vec3(4, 11);

This will initialize a vector of size 4, and all the elements will have the value of 11 like this: {11,11,11,11}.

Moreover, if we do not enter the data in the vector at the moment when we have declared the vector, we can add it later using the function push_back. The syntax of this function is:

vec1.push_back(value);

This will insert the value as the last element of the vector.

Access the Values of a Vector in C++

There are certain methods for iteration in vectors.

Function Purpose
begin() This function returns an iterator pointer to the first element of the vector.
end() This function returns an iterator pointer to the last element of the vector.
size() This function returns the total size of the vector, which means having how many elements.
at(p) This function returns the pointer to the element at the position p in the vector.
empty() This function checks if the vector is empty or not.

These functions are demonstrated in the following code snippet:

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> vec1;
  for (int j = 1; j <= 5; j++) vec1.push_back(j + 1);
  cout << "Size: " << vec1.size() << endl;
  cout << "Output of begin and end functions: ";
  for (auto a = vec1.begin(); a != vec1.end(); ++a) cout << *a << " ";
  cout << endl;
  cout << "Element at position 3: " << vec1.at(3) << endl;
  return 0;
}

Output:

Size: 5
Output of begin and end functions: 2 3 4 5 6
Element at position 3: 5

Initialize 2-Dimensional Vectors in C++

Like 2D arrays, 2D vectors are also a vector of vectors. Each element of such a vector is a vector itself.

Like in Java jagged arrays, we can have a multiple-size vector at each position of a 2D vector. This behaves like a matrix having some number of rows and columns.

The difference is that it can have a variable number of columns in each row.

Syntax for declaration:

vector<vector<int>> vec1{{1, 1, 0}, {0, 2}, {2, 1, 3}};

As it is a 2D structure, we need two loops for iterating through this vector - one loop for traversing rows and the inner loop for traversing columns.

for (int a = 0; a < vec1.size(); a++) {
  for (int b = 0; b < vec1[a].size(); b++) cout << v1[a][b] << " ";

Ensure that the size() function doesn’t return the total number of elements in the vector. Instead, it returns the total number of vectors in this vector.

We can also initialize this vector by specifying the number of rows and columns like this:

int rows = 3;
int columns = 4;
vector<vector<int>> vec1(rows, vector<int>(columns));

Let’s look at the complete code for creating 2-D vectors:

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int rows = 3;
  int columns = 4;
  vector<vector<int>> vec(rows, vector<int>(columns));
  for (int a = 0; a < rows; a++)  // loop for initializing the vector
  {
    for (int b = 0; b < columns; b++) {
      vec[a][b] = a * b;
    }
    cout << endl;
  }
  for (int a = 0; a < rows; a++)  // loop for displaying the values of vector
  {
    for (int b = 0; b < columns; b++) {
      cout << vec[a][b] << " ";
    }
    cout << endl;
  }
  return 0;
}

Output:

0 0 0 0
0 1 2 3
0 2 4 6
Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn

Related Article - C++ Vector