view raw
nnrales nnrales - 5 months ago 42
C++ Question

How to compute distance between std::vector<int>::iterator and std::vector<int>::reverse_iterator?

I tried using std::distance like this :

vi::iterator frontIter = resVec.begin();
vi::reverse_iterator backIter = resVec.rbegin();

if(std::distance(frontIter , backIter))
std::cout << " ! " << std::endl;

But the compiler gives me this error.

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))

So how I find the distance between these two iterators. Better yet, is there a way to solve this problem without using the back_iterator, but two standard iterators ?

for(size idx = 0 ; idx < vec.size() ; ++idx)
if(idx == n)

if(vec[idx] < partVal) // insert in front of partVal

*frontIter = vec[idx];
else // insert at back of n
*backIter = vec[idx];


Note :

using vi = std::vector<int>;
using size = std::size_t;


Any reverse iterator can be converted to its underlying forward iterator via base().

So what you want is:

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

Which will give you the same result as v.size().