resizing vector via a pointer to the vector

Discussion in 'C++' started by Sean Dettrick, Jul 30, 2003.

  1. 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:
    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 Dettrick, Jul 30, 2003
    1. Advertisements

  2. (*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:


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


    Learn the precedence of operators.

    Victor Bazarov, Jul 30, 2003
    1. Advertisements

  3. Thanks very much!
    Sean Dettrick, Jul 31, 2003
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.