How to access the contents of a vector from a pointer to the vector in C++?
Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:
#include <iostream>
#include <vector>
using namespace std;
void foo(vector<int>* a)
{
cout << a->at(0) << a->at(1) << a->at(2) << endl;
// expected result is "123"
}
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
foo(&a);
}
While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.
Here's the references version of the above program:
#include <iostream>
#include <vector>
using namespace std;
void foo(const vector<int>& a)
{
cout << a[0] << a[1] << a[2] << endl;
// expected result is "123"
}
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
foo(a);
}
As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.
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;
}