相同类型的集合有2个迭代器:
typename TFunction <T>::Type ::const_iterator i1 = f1.begin();
typename TFunction <T>::Type ::const_iterator i2 = f2.begin();
经过几个步骤,i1指向f1的某些元素,其索引为index1(可能未知)。我需要将第二个迭代器i2设置为具有与index1相等索引的f2元素...
是否可以在不将i1转换为索引的情况下完成此操作?
使用std::advance
如:
std::advance(it2, index1); //increments it2 index1 times!
完毕!
如果您不知道的值index1
,则始终可以使用当前 值来计算它it1
:
auto index1 = std::distance(f1.begin(), it1);
:-)
请注意std::advance
返回,void
因此您不能编写此代码:
fun(f2.begin(), std::advance(it2, index1)); //error
相反,如果您必须编写以下代码:
std::advance(it2, index1); //first advance
fun(f2.begin(), it2); //then use it
因此,为了减轻这种用法,std::next
在C ++ 11中添加了:
fun(f2.begin(), std::next(f2.begin(), index1)); //ok, don't even need it2!
顺便说一句,在C ++ 11中,您可以使用auto
而不是类型名来代替:
auto it1 = f1.cbegin(); //cbegin() returns const_iterator
auto it2 = f2.cbegin(); //cbegin() returns const_iterator
希望能有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句