Tutorials  /  Python

A Practical Guide to 2D Vectors in C++

Ccentron Redaktion · May 2024 ·4 min read ·Python, Tutorial

In the world of C++ programming, 2D vectors, also known as vectors of vectors, are a fundamental concept. They serve as the foundation for creating dynamic structures such as matrices and tables. However, before delving into the depths of 2D vectors in C++, it's advisable to gain a basic understanding of one-dimensional vectors in C++.

Including the Vector Header File

To use vectors in C++, you need to include the appropriate header files at the beginning of your program. For 2D vectors, we typically use:

Code
#include

Alternatively, you can include all the necessary Standard Template Libraries (STL) at once using the following command:

Code
#include<bits/stdc++.h>
VM

Matching infrastructure at centron

Scripts and services eventually need an environment that keeps running: ccloud³ VMs from €3.12 per month, billed by the hour. Rent a cloud server →

Initialization of 2D Vectors in C++

There are different ways to initialize 2D vectors in C++, and two common methods are explained below.

1. Initialization with Known Elements

Code
#include
#include
using namespace std;

int main(){
    vector<vector> v {{1, 0, 1}, {0, 1}, {1, 0, 1}}; 
    for(int i=0; i<v.size(); i++){
        for(int j=0; j<v[i].size(); j++)
            cout << v[i][j] << " ";
        cout << endl;
    }					   
}

Output:

Code
1 0 1 
0 1 
1 0 1

Each value within the curly braces, such as `{1, 0, 1}` and `{0, 1}`, represents an individual vector within the 2D vector.

2. Initialization with Specified Size

Code
#include
#include
using namespace std;

int main(){
    int num_col = 3; // Number of columns
    int num_row = 4; // Number of rows
    vector row(num_col, 0); // Initialize a single row
    vector<vector> v(num_row, row); // Initialize the 2D vector

    for(int i=0; i<v.size(); i++){
        for(int j=0; j<v[i].size(); j++)
            cout << v[i][j] << " ";
        cout << endl;
    }					   
}

Output:

Code
0 0 0 
0 0 0 
0 0 0 
0 0 0

In this code, first, a one-dimensional vector `row` is created, representing each row of the 2D vector. Then, the entire 2D vector is initialized by repeating this row.

A shorter way to achieve the same result is:

Code
#include
#include
using namespace std;

int main(){
    int num_col = 3; // Number of columns
    int num_row = 4; // Number of rows
    vector<vector> v(num_row, vector(num_col, 0)); // Initialize the 2D vector

    for(int i=0; i<v.size(); i++){
        for(int j=0; j<v[i].size(); j++)
            cout << v[i][j] << " ";
        cout << endl;
    }					   
}

Using Iterators for 2D Vectors

Code
#include
#include
using namespace std;

int main(){
    vector<vector> v {{1, 0, 1}, {0, 1}, {1, 0, 1}}; 

    // Iterator for the 2D vector
    vector<vector>::iterator it1;

    // Iterator for each vector within the 2D vector
    vector::iterator it2;

    // Traverse a 2D vector using iterators
    for(it1 = v.begin(); it1 != v.end(); it1++){
        for(it2 = it1->begin(); it2 != it1->end(); it2++)
            cout << *it2 << " ";
        cout << endl;
    }					   
}

Output:

Code
1 0 1 
0 1 
1 0 1

Iterators are particularly useful for operations where precise positioning within the vector is required.

Manipulating 2D Vectors

Adding Elements

Code
// Initialize the 2D vector
vector<vector> v;

v.push_back({1, 0, 1});
v.push_back({0, 1});
v.push_back({1, 0, 1});

]

Removing Elements

Code
// Initialize the 2D vector
vector<vector> v;

v.push_back({1, 0, 1});
v.push_back({0, 1});
v.push_back({1, 0, 1});

Removing Elements

Code
// Remove the last vector from a 2D vector
v.pop_back();
Code
// Remove the second vector from a 2D vector
v.erase(it + 1);

To remove all vectors from the 2D vector, you can use the `clear()` function.

Conclusion

2D vectors in C++ are a versatile tool ideal for working with two-dimensional data structures like matrices and tables. Understanding their initialization, iteration, and manipulation is essential for solving problems that require such structures. We hope this guide has helped you with using 2D vectors in C++. Feel free to ask questions or leave comments for further clarification on this topic.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren