c++ - why should we use pointer for this code? -
i found following code tutorial of c++. in:
cout << "value of v = " << *v << endl;
you can see *v
used. can tell me why should not use v
instead of *v
?
#include "stdafx.h" #include <iostream> #include <vector> using namespace std; int main() { // create vector store int vector<int> vec; int i; // access 5 values vector for(i = 0; < 5; i++){ cout << "value of vec [" << << "] = " << vec[i] << endl; } // use iterator access values vector<int>::iterator v = vec.begin(); while( v != vec.end()) { cout << "value of v = " << *v << endl; v++; } cin.get(); cin.get(); return 0; }
the type of v
vector<int>::iterator v
therefore if tried do
<< v << endl;
you'd trying write iterator
output stream, whereas want int
. therefore, dereference iterator, use *
operator @ underlying object contained within iterator
<< *v << endl
Comments
Post a Comment