0

I have this 2d array:

vector<vector<int>> arr = {{1, 1}, 
                           {1, 3, 2}, 
                           {1, 6, 11, 6}};

I want to add the lasts elements of each row (1 + 2 + 6), and then the second-lasts (1 + 3 + 11), and so on ((1 + 6), (1)). How can I do that?

Btw sorry for my english (not native speaker).

1
  • 2
    This doesn't look like a matrix, nomatter how you interpret it. Commented Jun 18, 2021 at 18:14

1 Answer 1

1

You can do that by, for example,

  1. Calculate the maximum number of elements of the elements of arr.
  2. Iterate from 0 to the maximum number minus one.
  3. Retrieve the ith element counted from the last element with checking if the element has i element or more.
  4. Add the elements.
#include <iostream>
#include <vector>
using std::vector;

int main(void) {
    vector<vector<int>> arr = {{1, 1}, 
                               {1, 3, 2}, 
                               {1, 6, 11, 6}};

    size_t max_num = 0;
    for (size_t i = 0; i < arr.size(); i++) {
        if (max_num < arr[i].size()) max_num = arr[i].size();
    }
    for (size_t i = 0; i < max_num; i++) {
        int sum = 0;
        for (size_t j = 0; j < arr.size(); j++) {
            if (i < arr[j].size()) sum += arr[j][arr[j].size() - 1 - i];
        }
        std::cout << sum << '\n';
    }
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.