1

Error E0028 expression must have a constant. Can you tell me how to solve it?

int V = 5;
vector<int> adj[V];

This is full code :

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

void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
}
void BFSUtil(int u, vector<int> adj[],
    vector<bool>& visited)
{

    list<int> q;
    visited[u] = true;
    q.push_back(u);
    while (!q.empty()) {
        u = q.front();
        cout << u << " ";
        q.pop_front();
        for (int i = 0; i != adj[u].size(); ++i) {
            if (!visited[adj[u][i]]) {
                visited[adj[u][i]] = true;
                q.push_back(adj[u][i]);
            }
        }
    }
}

void BFS(vector<int> adj[], int V)
{
    vector<bool> visited(V, false);
    for (int u = 0; u < V; u++)
        if (visited[u] == false)
            BFSUtil(u, adj, visited);
}

int main()
{
    int V = 5;
    vector<int> adj[V];

    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
    BFS(adj, V);
    return 0;
}
JeJo
  • 30,635
  • 6
  • 49
  • 88
  • 2
    related/dupe: https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – NathanOliver Oct 14 '21 at 12:26
  • `vector adj[V];` is a c-array of `std::vector` is this is what you wanted then `V` needs to be a compile time constant. – Richard Critten Oct 14 '21 at 12:29
  • `vector adj[V];` is an anachronism. It says "I want to use standard containers" and it says "I dont want to use standard containers". It is mainly common on so-called tutorial sites, that you better don't use to learn – 463035818_is_not_an_ai Oct 14 '21 at 12:30
  • You could make `V` a constant: [https://godbolt.org/z/65c65Ta43](https://godbolt.org/z/65c65Ta43) – drescherjm Oct 14 '21 at 12:45

1 Answers1

2
vector<int> adj[V];
//          ^^^^^^

is a variable length array, and it is not part of C++ standard. Read more: Why aren't variable-length arrays part of the C++ standard?,

You should not be doing it, even though some compilers extensions can support it. It seems like your compiler does not support it as well/ by default the compiler extension is turned off. Hence, the error!


Can you tell me how to solve it?

You can use instead

std::vector<std::vector<int>> adj(V, std::vector<int>{});

It is a vector of vector integers, with V number of default initialized std::vector<int>{}. All your functions must adapt the changes accordingly.

As a side note, have a look at: Why is "using namespace std;" considered bad practice?

JeJo
  • 30,635
  • 6
  • 49
  • 88