check to see if vector index is empty

2019-07-15 19:00发布

问题:

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.

回答1:

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)); 
}


回答2:

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.



标签: c++ vector