Spook Spook - 10 months ago 62
C++ Question

Modifying two vectors of the same type in a for loop

I'd like to modify the values stored in two vectors of the same type T in the same loop.
For example, say I have two vectors of ints:

std::vector<int> student_ids;
std::vector<int> teacher_ids;

Now I'd like to loop through these two vectors at the same time, and simply show each value for now. For instance:

for(int id : student_ids, teacher_ids)
std::cout << id << "\n";

How would I be able to achieve that?


In this way you can iterate the two vectors in one loop but keep in mind to check for bounds if the sizes of the two vectors are not same.

std::vector <int>::iterator it1 = student_ids.begin();
std::vector <int>::iterator it2 = teacher_ids.begin();

for(; it1 != student_ids.end() || it2 != teacher_ids.end(); ++it1, ++it2) {
    if(it1 != student_ids.end())
        std::cout << "Student: " << *it1 << std::endl;
    if(it2 != teacher_ids.end())
        std::cout << "Teacher: " << *it2 << std::endl;

Else, if you are sure that the size of both the vectors are same, just replace the || with && and you can do away the if conditions within the loops like this:

for(; it1 != student_ids.end() && it2 != teacher_ids.end(); ++it1, ++it2) {
    std::cout << "Student: " << *it1 << std::endl;
    std::cout << "Teacher: " << *it2 << std::endl;