对于相同类型的集合,有2个迭代器:
    typename TFunction <T>::Type ::const_iterator i1 = f1.begin();
    typename TFunction <T>::Type ::const_iterator i2 = f2.begin();
在几个步骤之后,i1指向具有index = index1的f1的一些元素(可能不知道).我需要将第二个迭代器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而不是typename thingy:
auto it1 = f1.cbegin(); //cbegin() returns const_iterator
auto it2 = f2.cbegin(); //cbegin() returns const_iterator
希望有所帮助.
| 归档时间: | 
 | 
| 查看次数: | 787 次 | 
| 最近记录: |