c++vectorheap-memorypush-back

manipulation of Vectors created with new


Can anyone help with this...

vector<unsigned int> *vVec = new vector<unsigned int>;
        vVec .reserve(frankReservedSpace);

        start = std::clock();
        for(int f=0; f<sizeOfvec; f++)
        {   //Populate the newly created vector on the heap
            vVec .push_back(pArray[f]);
        }

I'm getting: error C2228: left of '.reserve' must have class/struct/union

I'm creating a vector using the new operator so that it outlives the function where it is created. This therefore gives me back a pointer to that vector on the heap rather than an actual vector object itself. therefore it won't let me carry out any .reserve() of push_backs. I can't see a way around it, can anyone help?


Solution

  • vVec is a pointer to a vector. Therefore you should be using the indirection (->) operator rather than the dot (.)

    vector<unsigned int> *vVec = new vector<unsigned int>;
    vVec->reserve(frankReservedSpace);
    
    start = std::clock();
    for(int f=0; f<sizeOfvec; f++)
    {  //Populate the newly created vector on the heap
       vVec->push_back(pArray[f]);
    }