vector.size() returns a size_t

Revision en4, by krngrvr09, 2016-07-05 11:59:23
vector<int> v;
cout<<v.size()-1;

The following will give you 18446744073709551615. This is because vector.size() returns a size_t type value, which is an alias for unsigned long int. In plain terms:

unsigned long int a=0;
cout<<a-1;

The above code will give the same result — 18446744073709551615.

Implications

for(int i=0;i<vector.size()-1;i++){
    ...
}

In the above for loop, if the vector has 0 elements, then the loop will be equivalent to:

for(int i=0;i<18446744073709551615;i++){
    ...
}

Which, I believe is not what you will be expecting. So the correct way to use for loops is the following:

for(int i=0;(i+1)<vector.size();i++){
    ...
}

---Edit---

As pointed out by Errichto and satyaki3794, we can just typecast vector.size() to an int, and use it normally. Like this:

for(int i=0;i<(int)vector.size()-1;i++){
    ...
}
Tags unsigned int, size_t, for loop

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English krngrvr09 2016-07-05 11:59:23 1
en3 English krngrvr09 2016-05-10 17:24:55 247 Tiny change: '-Edit---\nAs point' -
en2 English krngrvr09 2016-05-10 17:07:06 0 (published)
en1 English krngrvr09 2016-05-10 17:06:44 814 Initial revision (saved to drafts)