resizing vector via a pointer to the vector

S

Sean Dettrick

Hi,
Can anyone please tell me if the following is possible, and
if so, what is the correct syntax?

I'd like to resize a vector (and access other vector member functions)
via a pointer to that vector, e.g:
vector<int> x(10);
vector<int>* p = &x;
*p.resize( 5 );
cout << *p[0] << endl;
But the compiler throws an error: "request for member `resize' in
`p', which is of non-aggregate type `vector<int, allocator<int> > *'"

How do I dereference p to obtain an aggregate type?

Here's my complete code:
#include<vector>
#include<iostream>
using namespace std;
int main(){

// some data vectors:
vector<int> x( 10, 1 );
vector<float> y( 10, 2.);
vector<double> z( 10, 3.);

// try to resize via a pointer to the vector:
// (doesn't work)
vector<int>* p = &x;
*(p).resize( 5 );
cout << *(p)[0] << endl;

// a vector of pointers to the data vectors:
int Nentries=3;
vector< void* > entries(Nentries);
entries[0] = &x;
entries[1] = &y;
entries[2] = &z;

// try to resize each of the data vectors via the pointers:
// (doesn't work)
for ( int entry=0; entry<Nentries; entry++ ) *entries[entry].resize( 5 );

}

Any suggestions?
Thanks very much,
Sean
 
V

Victor Bazarov

Sean Dettrick said:
Hi,
Can anyone please tell me if the following is possible, and
if so, what is the correct syntax?

I'd like to resize a vector (and access other vector member functions)
via a pointer to that vector, e.g:
vector<int> x(10);
vector<int>* p = &x;
*p.resize( 5 );
cout << *p[0] << endl;
But the compiler throws an error: "request for member `resize' in
`p', which is of non-aggregate type `vector<int, allocator<int> > *'"

How do I dereference p to obtain an aggregate type?

(*p).resize(5);

or

p->resize(5);

the same goes for the operator []. If you want to reach
the zeroth element of the vector pointed to by 'p', you
need to put *p in parentheses:

(*p)[0]

otherwise you're indexing the vector from the pointer and
then trying to dereference the vector (doesn't compile):

*(p[0])

Learn the precedence of operators.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top