简体   繁体   中英

input 2D vector in main() c++

I am novice in vectors, I am tryind to input this 2D vector in main() function, but unable to do so.

    int main()
{
    int t, x, n;
        cin>>n;
        vector< vector <int> >  jail(n);
        for(int i=0; i<n; i++){
            jail[i].reserve(n);
            for(int j=0; j<n; j++){
                cin>>jail[i][j];
            }
        }   

        cout<< jailBreak(jail,n-1,0,0)<<endl;
}

Runtime error is that I need to input an garbage input in the beginning of the program. This ambiguous input has been bothering me for a long time now, thanx in advance for any advice on this.!

this line:

jail[i].reserve(n);

just tells vector to pre-allocate memory (it's just a hint to optimize further reallocs on push_back operations but does not guarantee allocation). You have to use resize instead which really allocates memory.

In your code:

for(int i=0; i<n; i++){
        jail[i].reserve(n);
        for(int j=0; j<n; j++){
            cin>>jail[i][j];
        }
    }

jail[i].reserve(n);

should be jail[i].resize(n)

cin>>jail[i][j]

Never seen that work before. cin in to a temporary and then push.

int temp;
std::cin >> temp;
jail[i].emplace_back(temp);

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