I have read the topic about “pointer”, but i still have some question.
// graph.cpp
struct Edge {
int from;
int to;
unsigned int id;
Edge(): from(0), to(0), id(0) {};
};
struct Vertex {
int label;
vector<Edge> edge;
};
class Graph: public vector<Vertex> {
int gid;
unsigned int edge_size;
};
if I declare a iterator in another file
bool get_forward_root (Graph &g, Vertex &v, vector<Edge*> &result) {
for(vector<Edge>::iterator it = v.edge.begin(); it != v.edge.end(); it++) {
if(v.label <= g[it->to].label)
result.push_back(&(*it));
}
}
In my understanding, it can be viewed as pointer, since v.edge.begin() is the first Edge object in vector<Edge>, but what is &(*it) ?
Question 2. What is the difference between g, &g, *g ?
In my understanding:
&gis the memory address.*gis a Graph pointer point to a graph object, so we can use Graph *g = new Graph();gis a Graph object
the difference between *g and g is how we use, for example the two conditions are the same:
condition 1:
Graph *g = new Graph();
g->gid = 0;
condition 2:
Graph g;
g.gid = 0;
Question 3.
what is below meaning?
Graph &g
and why we use g[it->to].label not &g[it->to].label
Thank very much:)
itacts like a pointer, but it’s not a pointer. If it were a pointer,&*itwould be the same asit. In the general case,&(*it)is the address (a real pointer) of the object that the iteratoritpoints to. We can assume here that the & operator was not overloaded.gisg.&gis the address of g.*gis the objectgpoints to (if g is a pointer). Your 2 conditions (I don’t understand why you call them conditions) do pretty much the same thing, yes.It’s called a reference. When defined, it should be immediately initialized. Think of a reference as another name of an object. (Better, read a book, see below).
All of your questions will be thoroughly answered in any decent C++ beginner book. I especially recommend Lippman’s C++ primer for this purpose. Find other good titles here.