As always, there are a lot of possibilities to achieve this. But to answer your initial question:
for (std::vector<myClass>::const_iterator i = myVec.begin(); i != myVec.end(); ++i) {
std::cout << *i << ", ";
size_t index = i - myVec.begin();
if (index % 5 == 0) {
std::cout << "\n";
}
}
This prints the value at the iterator position and the index in the vector. You calculate the difference between the begin()
of the vector and the current iterator position, which is the index.
While it is possible to do this, I wouldn't recommend it because you have an additional subtraction in every iteration. This is generally not a situation where iterators are very useful, as you've seen for yourself.
If you have access to a sufficiently modern C++ compiler (which I guess you do), you can use the very elegant range-based for-loops:
for (myClass& obj : myVec) {
std::cout << obj;
}
This "extracts" references to the objects in your vector. Of course, now you're even farther away from the index position because you can't use the iterator-subtraction trick. To solve your problem of keeping an index you can simply keep a separate index counter:
int i = 0;
for (myClass& obj : myVec) {
std::cout << obj << ", ";
if (i % 5 == 0) {
std::cout << "\n";
}
i++;
}
Or even use the very new C++20 feature of inline-initialized variables (I don't remember the official name for these):
for (int i = 0; myClass& obj : myVec) {
std::cout << obj << ", ";
if (i++ % 5 == 0) {
std::cout << "\n";
}
}
Or you can just use the classical for (int i = 0; i < size; i++) ...
, though this isn't as clear as the range-based for-loop version. With the range-based for-loop it's possible to instantly see that something is done with all objects in the vector.