What type to use when iterating std :: vector (without iterators)?

Perhaps this question is trivial, but thinking about it a second time, I wonder how to do the following correctly:

std::vector<K> v = ...;
for(T i=0; i<v.size(); ++i) {
  const K& t = v[i];
  // use t *and i*
}

What type should Tbe? int, unsigned int, int32_t, size_t(Which is a type v.size()) or any other suggestions? Please consider portability, inaccuracy, and performance and be objective in your answer.

Edit: I did not select iterators because he would also like to explicitly use index number i.

+5
source share
3 answers

i , size(), std::vector<K>::size_type. size_t . , , , / .

:

std::vector<K> v = ...;
for (std::vector<K>::iterator i = v.begin(); i != v.end(); ++i) {
  const K& t = *i;
  // use t
}

, ++ 0x:

std::vector<K> v = ...;
for (auto i = v.begin(); i != v.end(); ++i) {
  const K& t = *i;
  // use t
}

std::distance(), :

std::vector<K> v = ...;
for (auto i = v.begin(); i != v.end(); ++i) {
  const K& t = *i;
  size_t index = std::distance(v.begin(), i);
  // use t and index
}
+6

, v.size v[], std::vector<K>::size_type.

: , .

+3

T , .

, .

/ , - i, , , . v.size() size_t, T, v ≥ 2 31 ( 2 63), i . , ( 64- ), , T.

int32_t .


( OP:)

.

for (std::vector<K>::const_iterator cit = v.begin(); cit != v.end(); ++ cit) {
  const K& t = *cit;
  // ...
}

With Boost.Foreach you can turn this mess into

BOOST_FOREACH(const K& t, v) {
  // ...
}

In C ++ 0x, this becomes a built-in function (& sect; [stmt.ranged]), but AFAIK does not support compilers; it still:

for (const K& t : v) {
  // ...
}

But most compilers claiming to support C ++ 0x should allow auto:

for (auto cit = v.cbegin(); cit != v.cend(); ++ cit) {
   const K& t = *cit;
   // ...
}

or lambda expressions:

std::for_each(v.cbegin(), v.cend(), [](const K& t) { 
   ...
});
+3
source

All Articles