I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?

- 347,512
- 102
- 1,199
- 985

- 3,013
- 5
- 27
- 47
-
4Are you sure you want to use a pointer to a vector? It might make more sense to use a reference. See my post below. – Andrew Rasmussen Aug 04 '11 at 18:27
8 Answers
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!)
}

- 3,793
- 1
- 19
- 22
-
1
-
1@Don Reba - Not really; on most compilers an exception is thrown: http://stackoverflow.com/questions/550451/will-new-return-null-in-any-case – Seb Holzapfel Aug 04 '11 at 18:14
-
1Also, if `new` **did** return 0, **all** the operations on pointers would be bad, not just the reference initialization. – Seb Holzapfel Aug 04 '11 at 18:18
-
10I'd personally prefer `(*v)[2];` to `v->operator[](2)` as it's shorter and still retains the 'operator-y-ness of the operator'. – god of llamas Dec 30 '16 at 00:36
-
@godofllamas agreed. `(*v)[2]` says index 2 from where the pointer sits, correct? – mLstudent33 Aug 05 '19 at 08:19
-
[FROM YOUR CODE ->]vector
&vr = *v; [BUT] (*(any pointer)) is dereferencing the pointer, right? then we can do this ------> vector – illla Jul 24 '21 at 16:11vr = *v;[CAN YOU TELL WHY DID YOU USE "&"] -
1@illla the `&` is used to create a reference to an existing object, in this case the vector that is pointed at by `v`. Your alternative would create a *copy* of that vector in a second brand new vector. – Mark Ransom May 18 '22 at 18:50
-
@mLstudent33 I think you don't quite understand. The pointer only points to a single vector, so there's no index 2 on that. The `*v` takes the pointer out of the equation, so you're getting index 2 out of that vector. – Mark Ransom May 18 '22 at 18:54
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;
}

- 299,747
- 42
- 398
- 622

- 18,706
- 4
- 46
- 63
-
1up'd for "like any other pointer". I don't understand the question. You have a pointer, so you use `thing->member` instead of `thing.member`, and that's the only difference (in 99% of cases, etc.) – underscore_d Dec 28 '15 at 21:25
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.

- 14,912
- 10
- 45
- 81
-
This may be a stupid comment. But since you only use the at method, are there any advantages to use the syntax (*a)[1]? Personally I like that since I thinn it reflects my i tentions better and this makes it easier for me to read the code (with advantages I mean significant performance increase for at least one case) – patrik Oct 02 '14 at 22:34
-
@patrik I think you've stumbled across the biggest difference between `at` and `operator[]`. `at` is forced to do bounds checks that aren't required in a well written and debugged program; that probably accounts for the performance increase you saw. The downside of course is undefined behavior if you go beyond the bounds of the vector in either direction. – Mark Ransom May 18 '22 at 18:39
-
@MarkRansom I looks back at this comment now, 8 years after I saw it first and realize this should not really be an issue. Today I would rather say vector::at should be preferred, unless there is a good reason not to use it. From a secure coding perspective a bounds check would be required, unless there is a really good reason why it is not feasible. I may even have commented the wrong post btw... – patrik Aug 16 '22 at 15:15
-
@patrik every project will be different and have different priorities. I'm glad C++ gives you the choice between fast and safe, that's not a choice you can make in most languages. And many times `operator[]` will have bounds checking too in a debug build, even though it's not required to. – Mark Ransom Aug 16 '22 at 16:42
-
@MarkRansom Yes, I agree with you. My point is that range check mechanisms is a strong recommendation when it comes to secure coding practices, such as the OWASP recommendation (https://owasp.org/www-pdf-archive/OWASP_SCP_Quick_Reference_Guide_v2.pdf). I accept though, that the [] operation may indeed have a range check for some implementations and that this approach may not be the only way to do a range check. Secure coding is not just some bullshit recommendation no one follow. There are security certifications for companies, which may include the company to follow secure coding practices. – patrik Aug 23 '22 at 10:25
-
For me the main advantage of a pointer versus reference is that you can set it to nullptr to indicate it hasn't been initialized. AFAIK that isn't possible to do with references. "but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. " Using a pointer doesn't imply that this is something you have to deal with. It could just as well be a pointer to a stack variable, or it could be a pointer to data some other entity is responsible for managing the lifecycle and you're just say, sharing/borrowing the data. – Qwert Yuiop Apr 02 '23 at 14:35
vector<int> v;
v.push_back(906);
vector<int> * p = &v;
cout << (*p)[0] << endl;

- 299,747
- 42
- 398
- 622
You can access the iterator methods directly:
std::vector<int> *intVec;
std::vector<int>::iterator it;
for( it = intVec->begin(); it != intVec->end(); ++it )
{
}
If you want the array-access operator, you'd have to de-reference the pointer. For example:
std::vector<int> *intVec;
int val = (*intVec)[0];

- 10,492
- 3
- 28
- 30
There are a lot of solutions. For example you can use at()
method.
*I assumed that you a looking for equivalent to []
operator.

- 1,997
- 12
- 12
-
-
1@user815961 `v->size()` returns the number of elements in the vector – Praetorian Aug 04 '11 at 17:59
vector <int> numbers {10,20,30,40};
vector <int> *ptr {nullptr};
ptr = &numbers;
for(auto num: *ptr){
cout << num << endl;
}
cout << (*ptr).at(2) << endl; // 20
cout << "-------" << endl;
cout << ptr -> at(2) << endl; // 20

- 93
- 7
The easiest way use it as array is use vector::data()
member.

- 10,512
- 7
- 43
- 74
-
1The reason you use a vector is to abstract away the underlying implementation (contiguous array) behind it. This is going against object oriented principles, not to mention extremely inefficient because you are allocating an entire new array of size n, when you could just use vec->at(index). Not to mention, this has absolutely nothing to do with the original poster's question because you aren't using a pointer to a vector anywhere. – Andrew Rasmussen Aug 04 '11 at 18:25
-
I was just giving out an example, if we want to know the underlying type, we can use vector::value_type. but it's statically interpreted. the whole point I wanted to convey is data() is the member to get the underlying pointer. And that's what his question was. – sarat Aug 04 '11 at 18:49
-
No, the question was whether the `vector` could be read through a pointer. I don't see anything in the OP that indicates anything deeper than that. – underscore_d Dec 28 '15 at 21:26
-
@AndrewRasmussen could you explain the "allocating an entire new array of size n" part? Does calling data() do that? – user2635088 Oct 15 '20 at 11:51
-
Idk why you was copying the vector to a new array in your original edit. (that explains all the dislikes) You could've simply used the data pointer itself. (see this [example](https://www.cplusplus.com/reference/vector/vector/data/)) But the question was simply about how to do vec[x] if vec is a pointer. (*vec)[x] is the answer. Also there's the at(x) method, but note that also checks if it's out of bounds. – Puddle Jan 31 '22 at 22:54