Perhaps this question is trivial, but thinking a second time about it I wonder how to do the following really the right way:
std::vector<K> v = ...;
for(T i=0; i<v.size(); ++i) {
const K& t = v[i];
// use t *and i*
}
What type should T be? int, unsigned int, int32_t, size_t (which would be the type of v.size()) or any other suggestions? Please try to consider portability, error-proneness and performance and be objective in your answer.
Edit: I did not choose iterators, because it would also like to use the index number i explicitly.
The type of
ishould be the same as the return value ofsize(), which isstd::vector<K>::size_type. However, in practice,size_twill do just fine. If you use a signed integer type, then your compiler will probably warn about a signed/unsigned mismatch in the less-than comparison.Normally you would use an iterator for this anyway:
Or, in C++0x:
In response to your comment about using the vector index with iterators, consider the
std::distance()function which is constant time operation for vector iterators: