Possible Duplicate:
Can I declare variables of different types in the initialization of a for loop?
I'd like to have a for loop in c++ which constructs 2 different kinds of vector iterator in the initialisation.
Here is a rough idea of what I would like:
std::vector<double> dubVec;
std::vector<int> intVec;
double result = 0;
dubVec.push_back(3.14);
intVec.push_back(1);
typedef std::vector<int>::iterator intIter;
typedef std::vector<double>::iterator dubIter;
for (intIter i = intVec.begin(), dubIter j = dubVec.begin(); i != intVec.end(); ++i, ++j)
{
result += (*i) * (*j);
}
Anyone know what is the standard to do in this situation? I can't just use a vector of double for the intVec because I'm looking for a general solution. [i.e. I might have some function f which takes int to double and then calculate f(*i) * (*j)]
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.
Yes, C Compiler allows us to define Multiple Initializations and Increments in the “for” loop. The image below is the program for Multiple Initializations and Increments. In the above program, two variable i and j has been initialized and incremented. A comma has separated each initialization and incrementation.
To compare the values that two iterators are pointing at, dereference the iterators first, and then use a comparison operator. Operator= -- Assign the iterator to a new position (typically the start or end of the container's elements).
You can't declare variables of different types inside a for
loop.
Just declare them outside:
intIter i = intVec.begin();
dubIter j = dubVec.begin();
for (; i != intVec.end(); ++i && ++j)
{
}
You could declare a std::pair
with first
and second
as the iterator types:
for (std::pair<intIter, dubIter> i(intVec.begin(), dubVec.begin());
i.first != intVec.end() /* && i.second != dubVec.end() */;
++i.first, ++i.second)
{
result += (*i.first) * (*i.second);
}
Check out the zip iterator. It does exactly what you want: parallel iterate over two or more sequences simultaneously. Using that, I'd write it as:
using namespace boost;
for (auto i=make_zip_iterator(make_tuple(dubVec.begin(), intVec.begin())),
ie=make_zip_iterator(make_tuple(dubVec.end(), intVec.end()));
i!=ie; ++i)
{
// ...
}
Admittedly, this get's a little more complicated if you don't have support for auto
or other type inference in your specific case, but it can still be quite nice with a typedef.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With