0

I have this constructor

class Vertex
{
    Vertex();
    ~Vertex();

    Edge* adjacencies;
};

I wanted there to be array of adjacencies, but it couldn't build. So I've created a pointer (Edge is my created class too).

And I have this piece of code with foreach loop that must iterate on all adjacencies, but, of course, it not compiles.

Vertex getted_vertex = vertexQueve.top();
for(Edge & e: getted_vertex.adjacencies)
            {
                Vertex v = Vertex(e._idFrom);
            }

Should I change the constructor or the loop?

1
  • 1
    Use std::vector and you can have everything you want from an array. Commented Apr 3, 2016 at 8:31

3 Answers 3

2

Simply use:

class Vertex
{
public:
    Vertex();
    ~Vertex();

    std::vector<Edge> adjacencies;
    // or std::vector<Edge*> adjacencies;
};

Fill it like that:

Vertex vertex;
vertex.adjacencies.push_back( Edge() );
// or vertex.adjacencies.push_back( new Edge() );

Later, to iterate on adjacencies:

Vertex vertex;
for ( std::vector<Edge>::const_iterator edge = vertex.adjacencies.begin();
      // or std::vector<Edge*>::const_iterator edge = vertex.adjacencies.begin();
      edge != vertex.adjacencies.end();
      ++edge )
{
    Edge& edgeRef = *edge;
    // simply use edgeRef

    // or Edge* edgePtr = *edge;
}

If storing Edge* in the vector, you may need to delete them from Vertex destructor.

Sign up to request clarification or add additional context in comments.

1 Comment

You can still use a foreach / range for here as the OP wishes.
2

You need your constructor and destructor to be public and a container for your edges, something like:

class Vertex
{
public:
    Vertex();
    ~Vertex();
private:
    vector<Edge> adjacencies;
};

Comments

0

1st, you have to place destructor, constructor in the public space and "adjancencies" in the private space. to create a dynamic array, you have to take its size first. then use this statement:

adjancencies = new Edge[i]l; // i refers to the size of the dynamic 1D array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.