gpt4 book ai didi

c++ - 模板 vector

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:53 25 4
gpt4 key购买 nike

我为一个类声明了一个模板,并试图将该类用作后续类中的 vector 。这是我的代码:

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

template <typename L>

class AdjacencyListVertex {

public:
L data;

vector<int> edges;

AdjacencyListVertex() {
data = -1;
}

AdjacencyListVertex(L _data) {
data = _data;
}

void add_edge(int other) {
edges.push_back(other) ;
}

void print(int i) {
cout << " vertex[" << i << "] '" << data << "' connected to:";
for (int j = 0; j < edges.size(); j++) {
cout << " " << edges.at(j);
}
cout << endl;
}
};

template <typename L>
class AdjacencyListGraph {
public:
vector<typedef AdjacencyListVertex*> vertices;

AdjacencyListGraph(int size) {
vertices = vector<typedef AdjacencyListVertex*> (size, AdjacencyListVertex<L>());
}

void add_vertex(int position, L data) {
vertices.at(position) = AdjacencyListVertex<L>(data);
}


void add_edge(int vertex1, int vertex2) {
vertices.at(vertex1).add_edge(vertex2);
}

void print() {
cout << "AdjacencyListGraph:" << endl;
for (int i = 0; i < vertices.size(); i++) {
if (vertices.at(i).data != -1) vertices.at(i).print(i);
}
}
};



int main(int argc, char** argv) {


AdjacencyListGraph<string> alg_str = AdjacencyListGraph<string>(5);

alg_str.add_vertex(0, "alg_str vertex 0");
alg_str.add_vertex(1, "alg_str vertex 1");
alg_str.add_vertex(2, "alg_str vertex 2");
alg_str.add_vertex(3, "alg_str vertex 3");
alg_str.add_vertex(4, "alg_str vertex 4");

alg_str.add_edge(0, 1);
alg_str.add_edge(1, 0);
alg_str.add_edge(1, 3);
alg_str.add_edge(3, 4);


}

我不断收到错误:

graphs.cpp:38: error: template argument 1 is invalid
graphs.cpp:38: error: template argument 2 is invalid
graphs.cpp: In constructor ‘AdjacencyListGraph<L>::AdjacencyListGraph(int)’:
graphs.cpp:41: error: template argument 1 is invalid
graphs.cpp:41: error: template argument 2 is invalid
graphs.cpp: In member function ‘void AdjacencyListGraph<L>::add_vertex(int, L)’:
graphs.cpp:48: error: request for member ‘at’ in ‘((AdjacencyListGraph<L>*)this)- >AdjacencyListGraph<L>::vertices’, which is of non-class type ‘int’
graphs.cpp: In member function ‘void AdjacencyListGraph<L>::add_edge(int, int)’:
graphs.cpp:55: error: request for member ‘at’ in ‘((AdjacencyListGraph<L>*)this)->AdjacencyListGraph<L>::vertices’, which is of non-class type ‘int’
graphs.cpp: In member function ‘void AdjacencyListGraph<L>::print()’:

这是行中的一个错误: vector 顶点;

我在 vector 的定义中犯了什么错误?

最佳答案

你的语法有误。您只是在猜测一些关键字吗?

你需要这样的东西:

std::vector<AdjacencyListVertex<L>*> vertices;

也许您的意思是对列表类型进行类型定义:

typedef AdjacencyListVertex<L> ListType;

std::vector<ListType*> vertices;

关于c++ - 模板 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8177327/

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