#include <iostream>
#include <vector>
using namespace std;
int main ()
{
vector <int> qwerty;
qwerty.push_back(5);
vector <int>* p = &qwerty;
cout << p[0]; //error: no match for 'operator<<' in 'std::cout << * p'
}
I'm g开发者_如何学Pythonenerally unclear on how to use pointers with vectors, so I'm pretty mystified as to why this is not working. To my mind, this should print 5 to screen.
// either
cout << (*p)[0];
// or
cout << p->operator[](0);
Your 'cout' line is equivalent to:
cout << qwerty;
because p is a pointer to qwerty, which you then dereference with [0].
qwerty is a vector of type int, which can't be printed directly.
If you look at http://www.cplusplus.com/reference/stl/vector/ , you can see there is a class method for [] overload, so qwerty[0] would return an int.
So cout << qwerty[0];
would work.
To better understand what does "p[0]" mean, you can try the following statement:
cout << p[0][0];
this statement will enable you to print out "5" on the console. Because p[0] return the object reference "qwerty", then since vector object support index operation, you can use (p[0])[0] to get the first element in the vector.
精彩评论