Simon Elliott wrote:
#include <vector>
#include <iostream>
int main (int argc, char *argv[])
{
std::vector<int > vi;
vi.push_back(1) ;
vi.push_back(2) ;
vi.push_back(3) ;
int* pi = vi.begin();
std::cout << "result:" << *pi << std::endl;
return(0);
}
This compiles and runs as I'd expect in Borland C++ Builder 6, but
gives the following error in g++:
test_vectors.cp p:9: error: cannot convert
`__gnu_cxx::__n ormal_iterator< int*, std::vector<int ,
std::allocator< int> > >' to `int*' in initialization
I can't see where I'm going wrong here: I was under the impression that
random access iterators could be assigned to pointers.
Then you're under the wrong impression.
An iterator is an iterator, which in fact is a concept, not a type. It
has operations on it and corresponding semantics.
A pointer has the same operations and semantics, and can be used as an
iterator if your container is a C style array (among others), but that
does not mean that a char* is the same as a std::vector<cha r>::iterator.
In many implementations it is actually a typedef for char*, but not
necessarily so, it's implementation specific.
In much the same way a char* is not the same as an int*, a
std::vector<cha r>::iterator is not the same as a char*, in many cases
they are interchangable, but you are going against the type system, and
invoking at best implementation specific behaviour.
Stick to the correct types and you'll be fine.
Perhaps you meant to say:
int* pi = &(*(vi.begin()) );
Or better:
std::vector<int >::iterator pi = vi.begin();
The reason is in the semantics. This is also how you implement smart
pointers... they behave like a pointer, in that you can dereference them
and get to the pointeee, but are clearly more than a pointer, and not
equivalent.
Hope that helps.
Ben
--
I'm not just a number. To many, I'm known as a string...