4

In my code, I need to do this:

if (edges[j].ConnectedToNode() != i) //problem line
{
    edges.push_back(Edge(i, j, nodes[i].Position(), nodes[j].Position(), distanceToNode)); 
}

however, there is a possibility that edges[j] does not exist yet. how can I test for this to avoid and index out-of-range exception? (This is to do with path nodes, essentially if there is an edge connecting j to i, I don't want to add another from i to j.

Dollarslice
  • 9,917
  • 22
  • 59
  • 87
  • It looks like you are mixing indices. You are using j as an index for edges and also as an index for the nodes. push_back will append a copy of the Edge object you are creating to the edges array. It won't necessarily go to the jth index. Consider using the boost::graph library. – David Nehme Jan 25 '12 at 16:36
  • you're absolutely right, I'm in the middle of updating my code and edges is changing from a vector to a vector of maps from indices to edges – Dollarslice Jan 25 '12 at 17:08

2 Answers2

8

Before accessing edges[j] check that j < edges.size().

EDIT:

To illustrate what Mark Ransom commented:

if (j < edges.size() && edges[j].ConnectedToNode() != i) //problem line
{
    edges.push_back(Edge(i, j, nodes[i].Position(), nodes[j].Position(), distanceToNode)); 
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • 3
    This is where the short-circuiting behavior of `&&` and `||` comes in handy - you can put that check first in the `if` statement and the second part won't won't be executed, so there's no chance of out-of-range access. – Mark Ransom Jan 25 '12 at 16:31
0

You can do this by checking the size of the vector:

if(edges.size() <= i) // will be false if i is too large

If this is the case, you have to resize the vector:

    edges.resize(j + 1);

Depending on the density of your adjacency-list, you will get a very sparse vector (most entries will not be used). In that case you should consider using a std::map<int, int> or something like that. This has the benefit that a map automatically creates a new index, if none exists for the given key.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283