vector.size() returns an size_t

Правка en2, от krngrvr09, 2016-05-10 17:07:06
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++){
    ...
}
Теги unsigned int, size_t, for loop

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en4 Английский krngrvr09 2016-07-05 11:59:23 1
en3 Английский krngrvr09 2016-05-10 17:24:55 247 Tiny change: '-Edit---\nAs point' -
en2 Английский krngrvr09 2016-05-10 17:07:06 0 (published)
en1 Английский krngrvr09 2016-05-10 17:06:44 814 Initial revision (saved to drafts)