0

Suppose I have two vectors of the same length:

std::vector<int> v1, v2;

if I have to iterate over both of it, which approach should I use:

for(size_t i = 0; i < v1.size(); ++i) { //...}

or

for(auto i = v1.begin(), j=v2.begin(); i != v1.end(); ++i, ++j) {//...}

Do both of these approaches always equal when optimized by compiler?

vladkkkkk
  • 270
  • 2
  • 12
  • 1
    You're comparing two different things, in the first loop you're referring only one vector. – Maroun Nov 06 '15 at 18:12
  • @MarounMaroun probably it is assumed that `v1.size() == v2.size()`. – lisyarus Nov 06 '15 at 18:13
  • see: http://stackoverflow.com/questions/7286755/how-can-i-iterate-over-two-vectors-simultaneously-using-boost-foreach – NathanOliver Nov 06 '15 at 18:13
  • @nmerci If you are sure about both are having same length first one seems good fit – Shankar Nov 06 '15 at 18:13
  • 2
    Instead of parallel vectors, use a `vector` where `data` defines the two integers – clcto Nov 06 '15 at 18:14
  • 1
    *"Do both of these approaches always equal when optimized by compiler?"* Measure. – Christian Hackl Nov 06 '15 at 18:16
  • If you use the index loop, access the vector with `at`. If you use the iterator loop, set the condition to `i != v1.end() && j != v2.end()`. Anything other is needlessly unsafe, as you might access `v2` out-of-bounds. – Emil Laine Nov 06 '15 at 18:18

0 Answers0