1

I am trying to print all the elements in a vector using a pointer. What is wrong in the code?

#include <bits/stdc++.h>
using namespace std;
int main() {
    vector <int> v = {1,2,3};
    int * p;
    for(p=v.begin();p != v.end();p++)
        cout<<*p<<" ";

}

I get a compilation error.

  • 1
    Welcome to Stack Overflow. It's generally best, if you get a compilation error, to paste the error into your question. It makes it easier for us to help you, and for search engines to find your question if people get the same error. :) – Ray Toal Aug 02 '19 at 05:18

2 Answers2

2

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. +1to 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
Martin Morterol
  • 2,560
  • 1
  • 10
  • 15
2

What is wrong in the code?

You are using p in the for loop as though it is an iterator. Iterators and pointers are related but they are not the same.

Change p to be an iterator. There is nothing to be gained by making it a pointer.

std::vector<int>::iterator p;
for(p=v.begin();p != v.end();p++)
    cout<<*p<<" ";
user12066
  • 613
  • 6
  • 23
R Sahu
  • 204,454
  • 14
  • 159
  • 270