How to access the contents of a vector from a pointer to the vector in C++?
I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?
There are many solutions, here's a few I've come up with:
int main(int nArgs, char ** vArgs)
{
vector<int> *v = new vector<int>(10);
v->at(2); //Retrieve using pointer to member
v->operator[](2); //Retrieve using pointer to operator member
v->size(); //Retrieve size
vector<int> &vr = *v; //Create a reference
vr[2]; //Normal access through reference
delete &vr; //Delete the reference. You could do the same with
//a pointer (but not both!)
}
Access it like any other pointer value:
std::vector<int>* v = new std::vector<int>();
v->push_back(0);
v->push_back(12);
v->push_back(1);
int twelve = v->at(1);
int one = (*v)[2];
// iterate it
for(std::vector<int>::const_iterator cit = v->begin(), e = v->end;
cit != e; ++cit)
{
int value = *cit;
}
// or, more perversely
for(int x = 0; x < v->size(); ++x)
{
int value = (*v)[x];
}
// Or -- with C++ 11 support
for(auto i : *v)
{
int value = i;
}