简体   繁体   中英

Access c++'s vector pointer's elements

How can I access the elements of the vector from vector pointer? In the following code what should be used instead of cout << v [0]; to print 10?

vector <int>* v; // the function parameter
v->push_back (10);
cout << v [0];

If you actually had a pointer to a vector, the correct way would be this:

cout << (*v)[0];

But you don't have a pointer to a vector. You have an uninitialized pointer, and your call to push_back is undefined behavior, as would be trying to print an element of this non-existent vector.

您可以使用v->at(0)v->operator[](0)

You shouldn't be using a pointer to a vector in the first place. It's much more reasonable to construct the vector on the stack:

std::vector<int> v;
v.push_back(10);
std::cout << v[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM