简体   繁体   中英

how to read input properly into a 2D vector, vector<vector<int>> in c++

i need to find the sum of each row using vector < vector > int > > on a matrix that has n columns, and n rows.

for example if this is the imput,

n = 4 
1 2 3 4
1 1 1 2
2 2 41 8
3 3 10 2

the output should be

10
5
53
18

this is my code so far:

vector<vector<int>> A;
int n, x;

cin >> n;

for (int i = 0; i < n; ++i) 
     for(int j = 0; j < n; ++j)
         cin >> x, A[i].emplace_back(x);

for(int i = 0 ; i < n ; ++i)
{
     int sum = accumulate(A[i].begin(), A[i].end(), 0);
     cout << sum << "\n";
}

Also I don t think that my reading of the matrix is good.

If you could help, it would be very appreciated!

Thank you!

To read into a 2D vector, you need to read into a 1D vector for each row, and then add that 1D vector to the 2D vector. You could do something like this:

for (int i = 0; i < n; ++i) 
{ 
  std::vector<int> row;
  for(int j = 0; j < n; ++j)
  {
    cin >> x;
    row.push_back(x);
  }
  A.push_back(row);
}

You could even allocate space for the entire 2D vector, and then read directly into the correct positions, like this:

auto A = std::vector<std::vector<int>>(n, std::vector<int>(n, 0));

for (int i = 0; i < n; ++i) 
  for(int j = 0; j < n; ++j)
    cin >> A[i][j];

You could simplify this even further as the comment suggests

auto A = std::vector<std::vector<int>>(n, std::vector<int>(n, 0));

for (auto &row : A) 
  for(auto &element : row)
    cin >> element;

Your code to sum up the rows seems reasonable.

int n, x;

cin >> n;
vector<vector<int>> A(n);

for (int i = 0; i < n; ++i) 
    for(int j = 0; j < n; ++j)
        cin >> x, A[i].push_back(x);

for(int i = 0 ; i < n ; ++i)
{
    int sum = accumulate(A[i].begin(), A[i].end(), 0);
    cout << sum << "\n";
}

The problem is you are trying to access A[i] when there are no vectors in the vector of vectors

vector<vector<int>> A ----> {}
vector<vector<int>> A(4) ----->{{}{}{}{}} // constructor initializes with 4 empty vectors 

now you can access A[i] which returns the ith vector object on which you can do a push_back to insert a element

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