Search code examples
c++memoryvectornew-operatorallocation

C++, I want to know how to allocate memory vector< pair<int, int> > *


I have an error _Has_unused_capacity() vector... I don't know how to allocate dynamic memory

I try to push_back, but the error occurred

vector< pair<int, int> > * v;

void Some_Function(){
   int m=3;
   int idx1=1;
   int idx2=2;
   int idx3=3;

   for(int i = 0; i<m; i++) {
       v[idx1].push_back(make_pair(idx2, idx3));      
       v[idx2].push_back(make_pair(idx1, idx3));
   }
}

Solution

  • You have a poiter to a vector which points to nowhere. Either allocate memory for your vector ( not recommended though) or don't use a pointer.

    vector< pair<int, int> > * v = new vector<pair<int, int>>[2];
    V[idx].push_back(make_pair(idx2, idx3));
    

    Don't forget to delete your vector when you are done with that.

    delete [] v;
    

    The better way is using smart pointers, here is an example with shared_ptr:

    #include <iostream>
    
    #include <vector>
    #include <memory>
    
    using namespace std;
    using vecPair = vector<pair<int, int>>;
    
    // deallocator for an array of vectors
    void deleter(vecPair* x)
    {
        delete[] x;
    }
    
    int main() {
        shared_ptr<vecPair> v;
        v.reset(new vecPair[2], deleter);
        int a = 1;
        int b = 2;
        int c = 3;
        int d = 4;
        v.get()[0].push_back(make_pair(a, b));
        v.get()[1].push_back(make_pair(c, d));
    }