Removing an STL Vector via a Pointer

I understand (at least I think it is) that pointers can be used as random STL iterators.

Why doesn't the following code compile if I did not point to the iterator?

vector<int> v{1, 2, 3}; v.erase(&v[0]); 
+7
c ++ iterator stl
source share
3 answers

You can pass pointers to algorithms such as std::sort , std::find or std::copy . These are templates that are customizable for everything that works as a suitable iterator.

This does not mean that different iterators are necessarily converted to each other.

The erase method of the std::vector<int> container can only work with iterators, only with elements of the same vector. As already mentioned, this can be implemented as a pointer, but usually it is not for the reasons indicated here: C ++ std :: vector <gt; :: iterator is not a pointer, why?

Consider std::find :

 template< class InputIt, class T > InputIt find( InputIt first, InputIt last, const T& value ); 

Here InputIt is a template parameter. The std::find pattern will work with any type of iterator that satisfies the requirements of the input iterator and whose operator* returns what can be compared to enter T Pointers work well here. As Fire Lancer correctly pointed out in the comment, both first and last must be of type InputIt .

Now compare this to std :: vector :: erase :

 iterator erase( const_iterator pos ); 

This takes const_iterator , which is one of the typedefs of the std::vector class. This is one specific type of iterator, not a template parameter.

+12
source share

The definition of vector.erase(...) is

iterator erase( const_iterator pos );

const iterator is the class itself. Therefore, if a simple pointer to this class were converted, this could be done. But I do not think it is possible.

But it is one thing to use it in a place where an iterator is expected, and another in algorithms.

If an iterator is required, only an iterator can be used.

Algorithms do not expect an iterator . Only an object for which the iterator concept is acquired (usually a begin and end returns the required iterator / pointer).

+1
source share

Although pointers are iterators, they are not the same as vector iterators (at least they don't have to be).

You can convert a pointer to a vector element in itertor using an iterator and pointer arithmetic like this.

 std::vector<int> v{1, 2, 3}; int* p = &v[0]; // a pointer auto v_iter = v.begin() + std::distance(v.data(), p); // an equivalent vector::iterator v.erase(v_iter); 

This only works with adjacent containers like std::vector or std::array .

0
source share

All Articles