Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a iterator with a pointer in C++

Tags:

c++

iterator

I am having problems building a library in VC9, but which was previously successfully built in VC6. Here is a part of the code:

size_t pos2find;
pos2find = J; 
std::vector<size_t>::iterator it(&pos2find);

And here is the error:

    error C2664: 'std::_Vector_iterator<_Ty,_Alloc>::_Vector_iterator(const std::_Vector_iterator<_Ty,_Alloc> &)' : cannot convert parameter 1 from 'size_t *' to 'const std::_Vector_iterator<_Ty,_Alloc> &'
    1>        with
    1>        [
    1>            _Ty=size_t,
    1>            _Alloc=std::allocator<size_t>
    1>        ]
    1>        Reason: cannot convert from 'size_t *' to 'const std::_Vector_iterator<_Ty,_Alloc>'

1>        with
1>        [
1>            _Ty=size_t,
1>            _Alloc=std::allocator<size_t>
1>        ]
1>        No constructor could take the source type, or constructor overload resolution was ambiguous

I appreciate any help.

EDIT: The code is from an open source library called "surfit", it is not my code, so i guess it's something that changed in the standard of the vector class. The iterator is then used in another std function:

std::vector<size_t>::iterator * ptr_from = fault->sort_by_first_begin;
std::vector<size_t>::iterator * ptr;
ptr = std::lower_bound(ptr_from, 
               fault->sort_by_first_end, 
               it, 
               ptr_size_t_less);

EDIT: I think i found a solution. After looking into std::lower_bound() :

template <class ForwardIterator, class T, class Compare>
  ForwardIterator lower_bound ( ForwardIterator first, ForwardIterator last,
                                const T& value, Compare comp );

Return iterator to lower bound
Returns an iterator pointing to the first element in the sorted range [first,last) which does not compare less than value. The comparison is done using either operator< for the first version, or comp for the second.

For the function to yield the expected result, the elements in the range shall already be ordered according to the same criterion (operator< or comp).

With this i just eliminated the it iterator and used lower_bound(first, last, &pos2find, comp);

like image 721
Adrian Avatar asked Feb 06 '26 15:02

Adrian


1 Answers

An iterator into a vector isn't guarantied to be a raw pointer. In VS6 vector<T>::iterator happened to be a T* so you could initialize the iterator with a T*. In later versions of VS the implementation of vector<T>::iterator changed to be a class type (as it's entitled to be) so code that made bad assumptions now fails to compile.

In any case the code you posted is buggy even if iterator is a T* since the pointer supplied is not a pointer into the vector.

like image 57
Motti Avatar answered Feb 09 '26 09:02

Motti