gpt4 book ai didi

c++ - c++中 "expression must be a modifiable lvalue"错误如何解决?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:08 35 4
gpt4 key购买 nike

const int ADJ_MATRIX[VERTEX_NUM][VERTEX_NUM]={   
{0,1,1,0,0,0,0,0},
{1,0,0,1,1,0,0,0},
{1,0,0,0,0,1,1,0},
{0,1,0,0,0,0,0,1},
{0,1,0,0,0,0,0,1},
{0,0,1,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,1,1,0,0,0}
};

typedef struct {
int vertex;
int matrix[VERTEX_NUM][VERTEX_NUM];
int vNum;
int eNum;
}Graph;

void buildGraph(Graph *graph){
graph->vNum = VERTEX_NUM;
graph->eNum = EDGE_NUM;
graph->matrix = ADJ_MATRIX;
}

错误出现在这句话:

graph->matrix = ADJ_MATRIX;

我是 C++ 新手。请告诉我为什么会出现这个问题以及如何解决?

我想将 ADJ_MATRIX 分配给 struct 中的矩阵。

最佳答案

如前所述,您不能在 C++ 中分配数组。这是因为编译器是一个吝啬鬼,因为编译器可以。它只是不会让你这样做......

...除非你欺骗它 ;)

template <typename T, int N>
struct square_matrix {
T data[N][N];
};

square_matrix<int, 10> a;
square_matrix<int, 10> b;
a = b; // fine, and actually assigns the .data arrays
a.data = b.data; // not allowed, compiler won't let you assign arrays

收获?现在代码需要一些小东西:

const square_matrix<int, VERTEX_NUM> ADJ_MATRIX={{ 
// blah blah
}}; // extra set of braces

typedef struct {
int vertex;
square_matrix<int, VERTEX_NUM> matrix;
int vNum;
int eNum;
}Graph;

void buildGraph(Graph *graph){
graph->vNum = VERTEX_NUM;
graph->eNum = EDGE_NUM;
graph->matrix = ADJ_MATRIX; // no change
}

要访问单元格,现在我们需要使用 graph->matrix.data[1][2]。这可以通过为 square_matrix 重载 operator[]operator() 来缓解。然而,这现在非常接近新的 std::array 类,或 Boost 等效的 boost::array,因此考虑这些可能是明智的。

关于c++ - c++中 "expression must be a modifiable lvalue"错误如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11843369/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com