c ++在for循环中初始化2个不同的迭代器 [英] c++ Initialising 2 different iterators in a for loop
本文介绍了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);
}
这篇关于c ++在for循环中初始化2个不同的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文