You can use a pointer, you just really don't want to
using namespace std;
int main() {
vector <int> v = {1,2,3};
int * p;
for(p=v.data(); p != (&v[v.size()-1])+1 ; p++)
cout<<*p<<" ";
}
p=v.data()
get you the pointer to the underlying element storage. See https://en.cppreference.com/w/cpp/container/vector/data
(&v[v.size()-1])
get you the address of the last element. +1
to get the first invalid address.
Now why your code doesn't compile.
The type of v.begin()
is std::vector::iterator. And an iterator cannot be cast to a pointer, that why you get the error :
cannot convert 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' to 'int*' in assignment
Now, how to print all the elements ?
vector <int> v = {1,2,3};
for(const int& e : v )
cout<<e<<" ";
Or with iterator :
vector <int> v = {1,2,3};
for(auto it = v.begin(); it != v.end() ; it++ )
cout<<*it<<" ";
Or the fancy way :
vector <int> v = {1,2,3};
std::copy( v.begin(), v.end(), std::ostream_iterator<int>( std::cout, " "));
Note:
In the general case, you can find the type of an expression with
template <class T>
struct td ;
using namespace std;
int main() {
vector <int> v ;
td<decltype(v.begin())> d;
}
This will give you an error with the type:
error: aggregate 'td<__gnu_cxx::__normal_iterator<int*, std::vector<int> > > d'
has incomplete type and cannot be defined