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