'Allocating memory to a list stl inside class through user

class Graph
{
    int num;
public:
        Graph(int n)
    {
        num = n;
    }
    list<int>* mylist = new list<int>[num];
    int* arr = new int[num];
    queue<pair < int, int >> pq;
    void accept();
};
int main()
{
    int n;
    cout << "Enter the number of vertices=";
    cin >> n;
    Graph g=Graph(n);
    g.accept();

}

I have this class of graph and I want to allocate memory of size 'num' which is the input from user in the main function. But it shows bad memory allocation.



Solution 1:[1]

You should learn about C++'s initialization, which is important and different from assignment.

In you example, initialization of mylist and arr happens before "initialization" of num (in fact, you are not initializing num, what you do is default-initialize it and then assign to it), hence the value of num is indeterminate at that point, and new complains "bad memory allocation".

Correct way of initializing members:

class Graph
{
    // write data members together,
    // their declaration positions in class do not indicate execution order
    int num;
    list<int>* mylist;
    int* arr;
    queue<pair < int, int >> pq;
    void accept();
public:
    Graph(int n)
      : num(n), mylist(new list<int>[n]), arr(new int[n])
    // member initializer list start with a ":" and followed by a list of
    //   member_name(initializer_for_this_member)
    // note their order should match the declaration order
    {
    // usually initialization all happen in the initializer list,
    // and constructor body is empty
    }

};

And as ????? ??? pointed out, you should avoid using new as much as possible and opt for standard container. In you example, I guess you want an dynamic array of list, and a dynamic array of number. You can use std::vector for this purpose.

class Graph
{
    int num;
    vector<list<int>> mylist;
    vector<int> arr;
    queue<pair < int, int >> pq;
    void accept();
public:
    Graph(int n) : num(n), mylist(n), arr(n) { }
    // initialize vector to contain n value-initialized objects
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1