3

This is my code:

vector<int>::iterator itv = vec.begin();
int *p;
p = itv; // ERROR!

I have a simple question: Why p can not get the value of itv, since p is an address and itv is also an address.

thanks. :D

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Alex
  • 39
  • 3

3 Answers3

4

In general an iterator is not defined as a raw pointer.

In old versions of some compilers the iterator of the class template std::vector was indeed defined as just a pointer.

But in modern compilers iterators of standard containers are usually defined as objects of some classes.

You could rewrite your code snippet the following way

vector<int>::iterator itv = vec.begin();
int *p;
p = &( *itv );

But a more simple and safer way is to write

int *p = vec.data();

Here is a demonstrative program.

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> vec = { 1, 2, 3, 4, 5 };
    
    for ( int *p = vec.data(); p != vec.data() + vec.size(); ++p )
    {
        std::cout << *p << ' ';
    }
    std::cout << '\n';
    
    return 0;
}

The program output is

1 2 3 4 5
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
3

Because vector<int>::iterator and int* are different types and C++ compiler does not know how to convert one to another, even though they are semantically similar. Also, Iterator is not necessarily the address in the memory (although it can be implemented as such).

Anyway, it is quite desired behavior. Imagine similar situation with

std::list<int>::iterator itv;

In this situation if you do the trick suggested in the comments &*itv, accessing the value under p++ will have undefined behavior.

pptaszni
  • 5,591
  • 5
  • 27
  • 43
0

I would like to add to all the previous answers that, despite the fact that raw pointers are not iterators by type, they fulfill all the random-access iterator requirements and can be used in STL algorithms.

For example:

int arr[N];
int *begin = arr;
int *end = begin + N;

// find
int *result = std::find(begin, end, value);
if (result != end) {
  // process found
}

// or sort
std::sort(begin, end);
alex_noname
  • 26,459
  • 5
  • 69
  • 86