2014-04-17 4 views
0

무향 그래프를 구현하려고하는데 작동중인 인접 목록을 만드는 데 문제가 있습니다.벡터의 벡터 벡터로 작업하는 방법은 무엇입니까?

코드 :

typedef int destination_t; 
typedef int weight_t; 

const weight_t weight_max=std::numeric_limits<int>::infinity(); 

class Neighbor 
{ 
public: 
    destination_t dest; 
    weight_t weight; 


    Neighbor(dest_t arg_dest, weight_t arg_weight){ 
    this->dest=arg_dest; 
    this->weight=arg_weight; 
    } 
}; 

그리고 그래프 : 주에서 그런

typedef std::vector<std::vector<Neighbor>> AdjList_t; 

class Graph 
{ 
public: 
    AdjList_t* AdjList; 
    int noOfVertices; 

    Graph(int V){ 
     AdjList=new AdjList_t(V); 
     this->noOfVertices=V; 
    } 
}; 

:

Graph G(2); 
G.AdjList[0].push_back(Neighbor(1,3)); 

컴파일하지 않음.

void std::vector<_Ty>::push_back(std::vector<Neighbor> &&)' : cannot convert parameter 1 from 'Neighbor' to 'std::vector<_Ty> &&' 

내가 여러 AdjList_t 개체를 만드는거야

AdjList=new AdjList_t(V); 

여기 같은 느낌,하지만 난 그냥 내가 함께 할 수있는 것처럼이 컨테이너의 크기를 설정하려면 :

AdjList_t List(2); 

하지만 주요 기능이 아니라 생성자에서 크기를 설정하려고합니다. 이 문제의 최선의 해결책은 무엇입니까?

+0

내가 부스트 그래프를 추천 할 수 있습니다. 그것은 그래프를위한 유용한 알고리즘과 데이터 구조를 많이 가지고 있습니다. – Danvil

답변

2

AdjList은 포인터입니다. 당신은 먼저 역 참조 할 필요가 :

(*G.AdjList)[0].push_back(Neighbor(1,3)); 

그러나 당신은 또한 메모리가 누수하고 포인터에 대한 필요가 없습니다, 그래서 내가 대신 그것을 제거하는 것이 좋습니다 :

typedef std::vector<std::vector<Neighbor>> AdjList_t; 

class Graph 
{ 
public: 
    AdjList_t AdjList; 
    int noOfVertices; 

    Graph(int V) : 
     AdjList(V), // This is how you call the constructor of a member 
     noOfVertices(V) 
    { 
    } 
}; 

int main() 
{ 
    Graph G(2); 
    G.AdjList[0].push_back(Neighbor(1,3)); 
    return 0; 
} 
관련 문제