简体   繁体   中英

How do I initialize and fill a vector of type vector<vector<int> >?

I am trying to return a write a function that creates a vector<vector<int> > and fills it and returns it. I am facing segmentation fault when trying to push elements into a vector<vector int> . Can anyone help me with this problem?

 vector<vector<int> > Solution::prettyPrint(int A) 
    {
        vector<vector<int>> arr;

        for(int x=1;x<(2*A);x++)
        {
            for(int y=1;y<(2*A);y++)
            {
                int xp=x,yp=y;
                if(x>A) xp=2*A-x;
                if(y>A) yp=2*A-y;

                int min=(xp<yp)?xp:yp;

                arr[x-1].push_back(A+1-min);
            }
        }

        return arr;
    }
arr[x-1].push_back(A+1-min);

You are trying to access arr[x-1] , but arr is an empty vector at that moment.

Since you know that arr is going to be of size 2*A-1 (at least that is what comes out from your code), you can put a

arr.resize(2*A-1); before the beginning of the outer loop, or directly when declaring it:

vector<vector<int> > arr(2*A-1);

You can go further and initialize even the inner vectors:

    for(int x=1;x<(2*A);x++)
    {
        arr[x-1].resize(2*A-1);
        for(int y=1;y<(2*A);y++)

and substitute

arr[x-1].push_back(A+1-min);

with

arr[x-1][y-1]=(A+1-min);

You need to do (assuming your matrix is of size ROWS x COLS )

vector<vector<int>> arr(ROWS, vector<int>(COLS));

and there is no more need for push_back anymore. The whole memory for the 2D array is now reserved so you can just use arr[i][j] to write into it. The code is also a bit faster than using push_back , since push_back does slow re-allocations when it needs to resize the vector.

However try avoiding such nested vectors as they are slow. Use a flat vector instead and map from 2D to 1D and vice versa.

That's right don't go in complex structures save your time and energy and make your project faster. Take a 2D array instead of push_back use arr[i][j]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM