I am a Python programmer trying to develop C++ proficiency. I have a silly question about vectors.
Suppose I have a vector like this
vector<int> adj;
Assume it contains some values. What does this operation do ?
adj[v].push_back(w)
Does it create vector of vectors ? How is it different from having a,
vector<vector<int>> adj
to begin with ?
Edit:: Associated code is a simple BFS on graph which compiles and runs perfectly.
class Graph
{
int V;
vector<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new vector<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
The BFS function is in GeeksForGeeks
In the provided class definition there is no vector.
class Graph
{
int V;
list<int> *adj;
public:
Graph(int V);
void addEdge(int v, int w);
void BFS(int s);
};
There is declared a data member that has the type pointer to std::list<int>
.
In the constructor of the class
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
there is allocated dynamically an array of objects of the type std::list<int>
and the address of the first element of the array is assigned to the data member adj
.
Thus in this statement
adj[v].push_back(w);
there is selected the element of the array with the index v
, adj[v]
, that represents an object of the type std::list<int>
and to this list is appended the object w
using the member function push_back
of the class template std::list
.
As for vectors then you indeed can declare a vector of vectors like
std::vector<std::vector<int>> v;
To use the subscript operator you have to create a required number of elements of the vector.
You can do it for example when the vector is declared.
std::vector<std::vector<int>> v( 10 );
This declaration declares a vector of vectors with 10 elements. Now you may use the subscript operator to add sub-vectors to the vector using the member function push_back
.
Here is a demonstrative program.
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> v( 10 );
for ( size_t i = 0; i < v.size(); i++ )
{
int value = 0;
for ( size_t j = 0; j < i + 1; j++ )
{
v[i]. push_back( value++ );
}
}
for ( const auto &sub_vec : v )
{
for ( const auto &item : sub_vec )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
return 0;
}
Its output is
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9