【问题标题】:Error E0028 expression must have a constant value错误 E0028 表达式必须有一个常量值
【发布时间】:2021-12-02 19:54:21
【问题描述】:

错误 E0028 表达式必须有一个常数。能告诉我怎么解决吗?

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

这是完整的代码:

#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;
}

【问题讨论】:

  • vector&lt;int&gt; adj[V]; is a c-array of std::vector&lt;int&gt; 这就是你想要的然后V 需要是编译时间常数。
  • vector&lt;int&gt; adj[V]; 是不合时宜的。它说“我想使用标准容器”,它说“我不想使用标准容器”。它主要在所谓的教程网站上常见,你最好不要用来学习
  • 您可以将V 设为常量:https://godbolt.org/z/65c65Ta43

标签: c++ algorithm multidimensional-array stdvector breadth-first-search


【解决方案1】:
vector<int> adj[V];
//          ^^^^^^

是一个variable length array,它不是 C++ 标准的一部分。 阅读更多:Why aren't variable-length arrays part of the C++ standard?,

你不应该这样做,即使some compilers extensions can support it。似乎您的编译器也不支持它/默认情况下编译器扩展已关闭。因此,错误!


你能告诉我怎么解决吗?

你可以改用

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

它是一个 vector 的向量 integers,默认初始化 std::vector&lt;int&gt;{} 的数量为 V。您的所有功能都必须相应地调整更改。

作为旁注,请查看:Why is "using namespace std;" considered bad practice?

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 2012-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多