模板向量

Vector of templates

本文关键字:向量      更新时间:2023-10-16

我为一个类声明了一个模板,我试图在随后的类中使用该类作为向量。下面是我的代码:

#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()’:

这是一个错误的行:顶点向量;

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

你的语法错了。你刚才是在猜关键词吗?

你需要这样写:

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

也许你的意思是定义列表类型:

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