jeudi 1 décembre 2016

How to compute distance between std::vector

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) 
    {
        continue;
    }   

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

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

}

Note :

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

Aucun commentaire:

Enregistrer un commentaire