simultaneous iteration over several vectors
Sep 21, 2010 at 9:44am UTC
Hi guys.
Is there a way to iterate simultaneously over two or more vector in c++?
The only thing I could think of is creating a loop and incrementing the iterator for all of them or using the [] operator which is slower.
Thanks.
Sep 21, 2010 at 11:56am UTC
Here's how I might do it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
vector<int > VectorA;
//stuff
vector<long > VectorB;
//stuff
vector<int >::iterator ItA = VectorA.begin();
vector<long >::iterator ItB = VectorB.begin();
while (true )
{
//
//do stuff with ItA and ItB
//
if (ItA != VectorA.end())
{
++ItA;
}
if (ItB != VectorB.end())
{
++ItB;
}
if (ItA == VectorA.end() && ItB == VectorB.end())
{
break ;
}
}
Last edited on Sep 21, 2010 at 11:57am UTC
Sep 21, 2010 at 1:07pm UTC
1 2 3 4 5 6 7
vector v, w;
iterator i, j;
for (i(v.begin()), j(w.begin()); i != v.end() && j != w.end(); ++i, ++j)
{
// do stuff
}
Last edited on Sep 21, 2010 at 1:07pm UTC
Sep 21, 2010 at 1:57pm UTC
NOTE: operator[] on vectors is not necessarily slower than iterators. However, iterators are a more general solution.
As a second observation, consider whether or not you can combine the vectors into a single vector of structs.
ie,
1 2 3 4 5 6 7 8 9 10 11 12
std::vector<int > intVec;
std::vector<long > longVec;
// becomes:
struct MyStruct
{
int anInt;
long aLong;
};
std::vector<MyStruct> vec;
Topic archived. No new replies allowed.