在for循环中修改两个相同类型的向量
Modifying two vectors of the same type in a for loop
我想在同一个循环中修改存储在相同类型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;
}
相关文章:
- 可以将两个相同类型的连续数组视为一个数组吗?
- [[no_unique_address]] 和两个相同类型的成员值
- C++将两个不同类型的向量的属性连接到新的向量中
- 如何在 c++ 中将两个不同类型的变量分配给一个变量
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 是否可以分配两个不同类型的结构
- C++ 重载运算符 - 减去两个相同类型的对象
- C++:从模板中构造具有两个相同类型名称的海峡
- 比较C 中的两个数据类型
- 在C++中,当两个向量类型不同时,如何将值存储到向量内部的向量中
- 在整数数据类型和连续两个字符类型之后.第 2 个字符的数据类型跳过..为什么
- 确定两个矢量类型或一个矢量类型与标量类型之间的二进制运算结果的正确大小类型
- 在没有公共getter的情况下,比较两个相同类型的对象是否相等
- 在c++中编写两个基本类型之间的重载比较(==)
- 如何在yacc联合中保存出现在同一规则下的两个相同类型的对象
- Bison:$$和$1指向相同的内存位置(两个指针类型的联合YYSTYPE)
- c++中两个float类型变量的精确比较
- 比较两个不同类型的值
- 不能从两个相同类型的源之一创建std::string