我尝试在特定Vertex中的矢量(Edge)的特定边缘上使用operator =。但是我收到了这个错误:
source_file.cpp:在成员函数'void Graph :: addEdges(int,int, int,int)':source_file.cpp:43:26:错误:'operator ='不匹配 (操作数类型是'std :: vector'和'Edge')
arr [source] .arr2 [dest] = Edge(source,dest,a,b);
#include <iostream>
#include <string>
#include <queue>
using namespace std;
const int maxVer = 60;
struct Edge{
int source;
int dest;
int a;
int b;
public:
Edge() : a(0), b(0){};
Edge(int source, int dest, int a, int b) : source(source), dest(dest), a(a), b(b) {}
Edge& operator=(const Edge& e){
source = e.source;
dest = e.dest;
a = e.a;
b = e.b;
return *this;
}
};
struct Vertex{
int parent;
int dest;
bool visited;
int numberEdges;
string str;
vector<Edge> arr2[maxVer-1];
};
class Graph{
int vertexNumber=0;
Vertex arr[maxVer];
queue<int> que;
public:
void addEdges(int source, int dest, int a, int b){
arr[source].arr2[dest] = Edge(source, dest, a, b);
arr[dest].arr2[source] = Edge(dest, source, b, a);
++arr[source].numberEdges;
++arr[dest].numberEdges;
}
};
int main(){
return 0;
}
有什么问题?我该如何解决?
谢谢!
答案 0 :(得分:3)
当你做Vertex
课时
vector<Edge> arr2[maxVer-1];
您没有声明一个大小为maxVer-1
元素的向量,您声明了maxVer-1
个向量的数组。
如果你想要一个载体,那么:
struct Vertex
{
// Declare the vector
vector<Edge> arr2;
// ... all other member variables...
// Add constructor with a member initializer list
Vertex()
: arr2(maxVer-1) // Initializes the vector to have maxVer-1 elements
{}
};
请注意已更改的订单,其中arr2
首先声明 。如果不是,则必须在构造函数成员初始化列表中添加所有其他成员的初始化。