Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get int position of vector loop

Tags:

c++

loops

vector

How to get int position of this loop? Thank you.

auto a = vect.begin();
auto b = vect2.begin();
auto c = vect3.begin();
for (; a != vect.end() && b != vect2.end() && c != vect3.end(); a++, b++, c++) {

}

I need to print values of other variable, but I need to get actual unsigned int position of this vector loop.

I need to print double vector using this position of this vector.

And how to get the last index of vector.

My problem is for for loop with multiple vectors and getting index from it next to use only last of indexes.

like image 215
Adam Avatar asked Jan 28 '23 07:01

Adam


2 Answers

As Angew shows, a simple indexed loop may be preferable when you need indices.

However, it is possible to get the index from an iterator as well:

auto a = vect.begin();
auto b = vect2.begin();
auto c = vect3.begin();
for (/*the loop conditions*/) {
    auto index = a - vect.begin();
}

It is also possible to get the index of a forward iterator using std::distance, but it would be unwise to use it in a loop, since the complexity will be linear for non-random-access iterators.

In the case of forward iterators (and generic code that must support forward iterators), you can write a loop which has both the index variable, and the iterators.

P.S. it is potentially preferable to use pre-increment with iterators. Probably only matters in debug build.

like image 91
eerorika Avatar answered Jan 29 '23 21:01

eerorika


It's simple: if you need indices, don't use iterators:

for (
  size_t idx = 0, idxEnd = std::min({vect.size(), vect2.size(), vect3.size()});
  idx < idxEnd;
  ++idx
)
{
  auto& obj1 = vect[idx];
  auto& obj2 = vect2[idx];
  auto& obj3 = vect3[idx];
}

(The above code initialises idxEnd once at the start of the loop, so that it's not needlessly recomputed at each iteration. It's just an optimisation).

like image 43
Angew is no longer proud of SO Avatar answered Jan 29 '23 21:01

Angew is no longer proud of SO