888
888

Reputation: 3406

Is it okay to use int instead of a size_t in looping over a vector?

If I have an integer vector

vector<int> vec;

and I loop in the following way

for(int i=0; i<vec.size(); i++)
{
   // do something
}

I get the signed/unsigned mismatch warning.

Of course I can declare i of type size_t to solve the problem. But if I keep i as int could I get some problem at runtime?

Upvotes: 2

Views: 361

Answers (3)

taocp
taocp

Reputation: 23644

Use the vector iterator instead.

vector<int>::iterator it;
for (it = vec.begin(); it!= vec.end(); ++it)
{
   //do something
}

Upvotes: 3

masoud
masoud

Reputation: 56479

Yes. For big numbers more than a value which a signed can store, it will be an undefined behavior.

However for small numbers which can be store in a signed it's OK.

Upvotes: 2

djechlin
djechlin

Reputation: 60788

Sure, if vec.size() is larger than than the maximum value for a signed int.

You can find maximum values in limits.h per this table.

Upvotes: 2

Related Questions