我试过像这样使用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;

最佳答案

可以通过base()将任何reverse iterator转换为其基础正向迭代器。

所以您想要的是:

std::distance(v.begin(), v.rbegin().base())


这将为您提供与v.size()相同的结果。

07-24 09:35