-3

Actually I have to do topological ordering of the vertices of a graph. for this I have been provided with the code template given below.

#include <iostream>
#include <algorithm>
#include <vector>

using std::vector;
using std::pair;

void dfs(vector<vector<int> > &adj, vector<int> &used, vector<int> &order, int x) {
    //write your code here
}

vector<int> toposort(vector<vector<int> > adj) {
    vector<int> used(adj.size(), 0);
    vector<int> order;
    //write your code here
    return order;
}

int main() {
    size_t n, m;
    std::cin >> n >> m;
    vector<vector<int> > adj(n, vector<int>());
    for (size_t i = 0; i < m; i++) {
        int x, y;
        std::cin >> x >> y;
        adj[x - 1].push_back(y - 1);
    }
    vector<int> order = toposort(adj);
    for (size_t i = 0; i < order.size(); i++) {
        std::cout << order[i] + 1 << " ";
    }
}

I am unable to understand the meaning of line " vector used(adj.size(), 0); ". Can anyone explain it please.

  • 3
    When learning C++, consider learning it, from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). What about it, don't you understand? It simply creates an object, of type `vector`, with a name `used`, and passing `adj.size()`, and `0` as arguments to its constructor. – Algirdas Preidžius May 12 '20 at 17:25
  • 2
    https://en.cppreference.com/w/cpp/container/vector/vector - see constructor #3. Why wasn't your first port of call the documentation / your text book / a high quality reference site? You could have answered your question in 30 seconds. – Jesper Juhl May 12 '20 at 17:26

1 Answers1

0
vector<int> used(adj.size(), 0);

This declares a local variable used of type vector<int> which is initialized using the two-argument constructor for vector that takes a size_t and an int.

That's the generic description; to understand the details, you need to know what the constructors of std::vector are. In particular there is

vector::vector(size_type n, const T& value, const Allocator& = Allocator());

which this will match, which constructs a vector of the specified size, initializing all elements with a copy of the specfied element value.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226