wenjie wrote:
there are many examples write the loop like this:
vector<intcoll;
for(int i = 0; i < coll.size(); ++i){
...
}
the function size() return type is size_t (unsigned int) ;
That may be the case for the implementation you are using. The standard says
that vector<int>::size() returns vector<int>::size_type, which is an
unsigned type big enough to represent any non-negative value of
vector<int>::difference_type.
I think if the size of coll bigger than the max value of int, it will
infinite loop, is that true?
(a) The return value of size will be squeezed in an int. Assuming that it
does not fit, you get undefined or implementation defined behavior.
(b) Assuming that coll.size() is converted to a negative int, the signed
int variable i will overflow, at which point your program will encounter
undefined behavior behavior again.
(c) Assuming that on your implementation, signed overflow just wraps around,
the variable i will however, just go through INT_MIN and approach
coll.size() from below. Then the loop terminates. However: depending on
what you are doing in the body of the loop, you will very likely trigger
some out-of-bounds UB before.
If that is true, Why not use like this:
for(size_t i = 0; i < coll.size(); ++i){
...
}
Much better. I would also consider:
for ( vector<int>::iterator iter = coll.begin();
iter != coll.end(); ++iter ) {
}
or
for ( vector<int>::size_type i = 0; i < coll.size(); ++i ) {
}
or
std::for_each( coll.begin(), coll.end(), some_function_object );
Best
Kai-Uwe Bux