fedemengo
fedemengo

Reputation: 696

Proper constructor for custom class

I'm currently using a custom object to represent the nodes of a graph. The graph is just a vector of such object.

class node {
public:
   unsigned int vertex;
   unsigned int weight;
   bool operator< (const node &x){ return weight < x.weight; }
   bool operator> (const node &x){ return weight > x.weight; }
};

The problem I'm facing is that I'm unable to come up with a proper constructor when I need to push_back() such object.

unsigned int u, v, w;
vector<node> G[V];
G[u-1].push_back({v-1, w}); 

This is the only way it works, but just with C++11. Is there a standard way to do that? If I try to compile with g++ without using the C++11 flag I get errors. I'm basically trying to implement an emplace_back().

EDIT: I need to compile my code with older version of C++

Upvotes: 1

Views: 81

Answers (1)

gsamaras
gsamaras

Reputation: 73366

This is the only way it works, but just with C++11.

And that's great, since that's the current state. Moreover this should work with C++14, C++17 and so on probably, thus you are on the safe side.


BTW, I guess that G[u-1].push_back({v-1, w}); is just a sample, since u is uninitialised, which is critical, let alone the other variables.


I was looking for a "backward compatibility" solution.

Define a constructor like this for example:

node(unsigned int v, unsigned int w) : vertex(v), weight(w) {}

and then do:

G[u - 1].push_back(node(v-1, w)); 

Upvotes: 4

Related Questions