我尝试使用std :: distance这样:
vi::iterator frontIter = resVec.begin();
vi::reverse_iterator backIter = resVec.rbegin();
if(std::distance(frontIter , backIter))
{
std::cout << " ! " << std::endl;
}
但是编译器给了我这个错误。
partion.cpp:46:39: note: candidate is:
In file included from /usr/include/c++/4.9/bits/stl_algobase.h:66:0,
from /usr/include/c++/4.9/vector:60,
from test.h:1,
from partion.cpp:1:
/usr/include/c++/4.9/bits/stl_iterator_base_funcs.h:114:5: note: template<class _InputIterator> typename std::iterator_traits<_Iterator>::difference_type std::distance(_InputIterator, _InputIterator)
distance(_InputIterator __first, _InputIterator __last)
^
/usr/include/c++/4.9/bits/stl_iterator_base_funcs.h:114:5: note: template argument deduction/substitution failed:
partion.cpp:46:39: note: deduced conflicting types for parameter ‘_InputIterator’ (‘__gnu_cxx::__normal_iterator<int*, std::vector<int> >’ and ‘std::reverse_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> > >’)
if(std::distance(frontIter , backIter))
所以我如何找到这两个迭代器之间的距离。更好的是,有没有办法解决这个问题而不使用back_iterator,而是使用两个标准迭代器?
for(size idx = 0 ; idx < vec.size() ; ++idx)
{
if(idx == n)
{
continue;
}
if(vec[idx] < partVal) // insert in front of partVal
{
*frontIter = vec[idx];
++frontIter;
}
else // insert at back of n
{
*backIter = vec[idx];
++backIter;
}
}
注意:
using vi = std::vector<int>;
using size = std::size_t;
答案 0 :(得分:2)
任何reverse iterator都可以通过base()
转换为其基础前向迭代器。
所以你想要的是:
std::distance(v.begin(), v.rbegin().base())
这会给你与v.size()
相同的结果。