Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check to see if vector index is empty

Tags:

c++

vector

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.

like image 279
Dollarslice Avatar asked Feb 21 '23 17:02

Dollarslice


1 Answers

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)); 
}
like image 56
hmjd Avatar answered Mar 08 '23 07:03

hmjd