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

3
  • 1
    related/dupe: stackoverflow.com/questions/32654108/… Commented Jan 4, 2021 at 15:07
  • 1
    For what it's worth, you can obtain the address of the referred-to element using &*itv so long as itv points to a valid element Commented Jan 4, 2021 at 15:07
  • Well, an iterator is not a pointer, so they are incompatibel. Commented Jan 4, 2021 at 15:10

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.