0
votes
vector <int> * v = new vector <int>;
v -> push_back (1);
cout << v[0]<< endl;  // error

Why can't I access the first element? I get this error

error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'std::vector')|

3

3 Answers

6
votes

Why would you allocate a vector with new? The main point of using vectors is to avoid having to use new.

vector<int> v;
v.push_back(1);
cout << v[0] << endl;

If for some strange reason you decide you really must use a pointer, then you can do

vector<int>* v = new vector<int>;
v->push_back(1);
cout << (*v)[0] << endl;

But really, allocating a vector with new makes little sense.

Perhaps you were a Java programmer before you tried C++? If so then don't try to program C++ in a Java style, they are very different languages. You will get into a horrible mess if you do.

1
votes

Because v is pointer to vector, but not reference or vector itself. Therefore v[0] gives you not what you likely expect. It gives you vector object itself. For which there is no stream output operator<< defined. You must use (*v)[0].

0
votes

It's very unlikely that you need to dynamically allocate a vector like this, but if you do have a pointer to a vector:

vector<int>* v = new vector<int>;

then the correct syntax to invoke the member functions is:

// dereferencing the pointer and then using the member functions
(*v).push_back(1);
cout << (*v)[0] << endl;

or

// using -> with the correct names of the member functions
v->push_back(1);
cout << v->operator[](0) << endl;