c ++在for循环中初始化2个不同的迭代器
问题描述:
我想在c ++中有一个for循环,它在初始化中构造了两种不同类型的向量迭代器。
I'd like to have a for loop in c++ which constructs 2 different kinds of vector iterator in the initialisation.
以下是我想要的概念:
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);
}
任何人都知道在这种情况下要做的标准是什么?
我不能只为intVec使用double的向量,因为我正在寻找一个通用的解决方案。 [即我可能有一些函数f,它将int加倍,然后计算f(* 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)]
答
您可以使用第一个
和第二个
声明 std :: pair
>作为迭代器类型:
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);
}