Saif AlHarthi
Saif AlHarthi

Reputation: 39

How to check if a vector of a vector exists?

I would like to know if a vector of vectors exist

for example

vector<vector<int> > edges;

Now I would like to check if edges[i] exists. I tried

if(edges[i] == NULL)

But it did not seem to work. How this can be resolved?

Clarification: I tried checking the size. I am just querying if its if initialized or not.

Upvotes: 2

Views: 10946

Answers (5)

kfsone
kfsone

Reputation: 24269

NULL (or more correctly, since you tagged C++11, nullptr) is used for checking pointers. You've declared a vector of concrete instances, so pointers don't apply, and if the test

if (i < edges.size())

then the vector is initialized - that is, constructed. You can check, next, whether it is populated:

if (i < edges.size() && !edges[i].empty())

however, this will not distinguish between uninitialized and currently empty, consider:

std::vector<int> v;
v.push_back(1);
v.pop_back(); // now it's empty again

bool uninitialized = v.empty(); // lies

It is empty, but it has been initialized and used, if that is your definition of initialized.

There is, however, one trick left, but it is tending towards undefined behavior.

if (i < edges.size() && edges[i].capacity() == 0)

This will tell you if the vector has any memory allocated. In the worst case scenario, if your vector aggressively frees, it will be equivalent to empty(). But in most standard implementations, a vector that has been populated will have non-zero capacity, whilst a vector that has not yet been used will have no capacity.

Again: it's not perfect, there are ways to tell the vector to release any capacity it has.

Upvotes: 1

Christian Hackl
Christian Hackl

Reputation: 27548

vector<vector<int> > edges;

Now I would like to check if edges[i] existis.

It seems that std::vector is the wrong (outer) data type for you. Perhaps you should use std::map instead:

std::map<int, std::vector<int>> edges;

if (edges.find(i) == edges.end()) {
  // does not exist
}

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65176

I think you might have confused checking whether an object "exists" which is not relevant here with bounds checking. If you want to check whether i is a valid index, just check if it's within the size of the vector:

if (i < edges.size())

Upvotes: 5

Adi Levin
Adi Levin

Reputation: 5243

You probably want to check if edges[i] is empty:

if (edges[i].empty())

Upvotes: 8

Trevor Hickey
Trevor Hickey

Reputation: 37924

Use vector.empty():

if (edges[i].empty()){
}

Or use vector.size():

if (edges[i].size() == 0){
}

Upvotes: 1

Related Questions