user3365101
user3365101

Reputation: 51

How to work with vector of vectors of objects?

I'm trying to implement undirected graph and I have some problems with creating a working adjacency list.

The code:

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;
    }
};

And the graph:

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;   
    }
};

Then in main:

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

Won't compile.

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

I feel like here

AdjList=new AdjList_t(V);

I'm creating multiple AdjList_t objects, but I just want to set the size of this container like I can do with:

AdjList_t List(2);

But I want to set the size in constructor, not in main function. What is the best solution to this problem?

Upvotes: 0

Views: 99

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44201

AdjList is a pointer. You need to dereference it first:

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

But you're also leaking memory and have no need for the pointer, so I would recommend eliminating it instead:

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;
}

Upvotes: 2

Related Questions