在for循环中修改两个相同类型的向量

Modifying two vectors of the same type in a for loop

本文关键字:两个 同类型 向量 循环 for 修改      更新时间:2023-10-16

我想在同一个循环中修改存储在相同类型T的两个向量中的值。例如,假设我有两个int型向量:

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

现在我想同时遍历这两个向量,并简单地显示每个值。例如:

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

我怎么才能做到呢?

这样,你可以在一个循环中迭代两个向量,但要记住,如果两个向量的大小不相同,检查边界

std::vector <int>::iterator it1 = student_ids.begin();
std::vector <int>::iterator it2 = teacher_ids.begin();
while(it1 != student_ids.end() || it2 != teacher_ids.end()) {
    if(it1 != student_ids.end()) {
        std::cout << "Student: " << *it1 << std::endl;
        ++it1;
    }
    if(it2 != teacher_ids.end()) {
        std::cout << "Teacher: " << *it2 << std::endl;
        ++it2;
    }
}

否则,如果您确定两个向量的大小相同,只需将||替换为&&,就可以像这样消除循环中的if条件:

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

如果你想在循环体中同时访问两个向量,唯一的方法是:

for (size_t i=0; i<std::max(student_ids.size(),teacher_ids.size()); i++) {
    if (i<student_ids.size())   // are there still students ? 
       cout << student_ids[i];
    cout <<" : ";
    if (i<teacher_ids.size())   // are there still teachers ? 
       cout << teacher_ids[i];
    cout<<endl;
}

但是我从你的例子中了解到,你正在寻找通过两个向量依次迭代,并且你正在寻找一种方便的方法来避免冗余代码。

如果你不想一个接一个地写两个循环,因为有一个非常复杂的体,如果你不想把这个体放入函数中,因为要访问很多局部变量,那就用一个lambda:

auto f = [&](int& id) {  cout << id<<endl; };  // could be more complex !   
for_each(student_ids.begin(), student_ids.end(), f); 
for_each(teacher_ids.begin(), teacher_ids.end(), f); 

或者,您可以使用临时合并的向量来迭代:

auto temp(student_ids); 
copy(teacher_ids.begin(), teacher_ids.end(), back_inserter(temp)); 
for (auto &id : temp )
   cout << id<<endl; 

在线演示

auto studentIterator = student_ids.begin();
auto teacherIterator = teacher_ids.begin();
auto studentIteratorEnd = student_ids.end(); // for tiny performance
auto teacherIteratorEnd = teacher_ids.end(); // the same
while (true)
{
  if (studentIterator != studentIteratorEnd)
  {
    std::cout << *studentIterator << std::endl;
    ++studentIterator;
  }
  if (teacherIterator != teacherIteratorEnd)
  {
    std::cout << *teacherIterator << std::endl;
    ++teacherIterator;
  }
  if (studentIterator == studentIteratorEnd && teacherIterator == teacherIteratorEnd)
    break;
}