【问题标题】:c++ error: "array must be initialized with a brace-enclosed initializer"c++ 错误:“数组必须用大括号括起来的初始化程序初始化”
【发布时间】:2020-05-30 02:13:31
【问题描述】:

我需要你的帮助。 我的功能是:(它的工作方式是真的)

#include <iostream>              
using namespace std;

#define V 4  
#define INF 999 
int floydWarshall(int graph[][V]){  

        int dist[V][V], i, j, k;  


        for (i = 0; i < V; i++)  
            for (j = 0; j < V; j++)  
                dist[i][j] = graph[i][j];  

        for (k = 0; k < V; k++)  
        {  

            for (i = 0; i < V; i++)  
            {  

                for (j = 0; j < V; j++)  
                {  

                    if (dist[i][k] + dist[k][j] < dist[i][j])  
                        dist[i][j] = dist[i][k] + dist[k][j];  
                }  
            }  
        }  

        return dist[V][V];  
    }

这行有错误数组必须用大括号括起来的初始化器初始化:

int dist[V][V] = floydWarshall(graph[][V]);

【问题讨论】:

  • return dist[V][V] 访问越界
  • 如果你使用 C++ 数组而不是 C 数组,这些东西会简单 1000 倍
  • 在 C++ 中尽量避免使用 #define 作为常量,而是使用 const int V = 4; 之类的东西。这包括重要的类型信息。
  • 提示:使用std::vector 作为数据容器并模拟二维结构。除非万不得已,否则不要乱用 C 数组。

标签: c++


【解决方案1】:

在许多情况下,您不能像使用其他变量或对象一样使用 C 数组。您不能将 C 数组按值传递给函数或从函数返回 C 数组。它将衰减为指向第一个元素的指针。因此std::array 是在 C++ 中引入的。它完全符合您对代码中 C 数组的期望:

#include <array>

constexpr int V = 4;

auto floydWarshall(std::array<std::array<int, V>, V> graph){
    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {  
            for (int j = 0; j < V; j++) {  
                if (graph[i][k] + graph[k][j] < graph[i][j])  
                    graph[i][j] = graph[i][k] + graph[k][j];  
            }  
        }  
    }  
    return graph;  
}

使用std::array,您可以将数组的副本传递给函数,而无需手动复制。您可以返回数组的副本,而不是使用动态内存分配和指针。

你使用这个函数

auto dist = floydWarshall(graph);

其中graph 的类型为std::array&lt;std::array&lt;int, V&gt;, V&gt;

【讨论】:

    猜你喜欢
    • 2011-05-18
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2016-04-14
    相关资源
    最近更新 更多