Search code examples
c++vectoruser-input

Input element by user into 2D vector c++


I'a trying to implement an algorithm, i want to input element by the user into 2D vector so that I have an element like this:

reference 1:
1 2 3
3 2 1
1 2 3

so I want to know how to push_back the element into 2D vector

my problem here:

std::vector<vector<int>> d;
//std::vector<int> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){ 
cout<<"ship"<<i+1<<":"<<' ';
    for(j=0; j<in; j++){
    cin>>temp;
    d.push_back(temp);// I don't know how to push_back here!!
    }
}

Solution

  • C++ is a strong type language, d is a vector of vector:

    for(i=0; i<in; i++){ 
        cout<<"ship"<<i+1<<":"<<' ';
        vector<int> row;
        for(j=0; j<in; j++){
          cin>>temp;
          row.push_back(temp);// I don't know how to push_back here!!
        }
        d.push_back(row);
    }