简体   繁体   中英

Change values of a matrix in C++

I need to get the upper triangle of a matrix by setting everything under the diagonal to 0.

Here is the code I wrote:

#include <iostream>
#include <vector>
using namespace std;

vector<vector <int>> upper_triangle(vector<vector <int>> n) {
    int rij = n.size();
    int kolom = n.size();
    vector<vector<int>> result = n;
    for (int i = 0; i < rij; i++) {
        for (int j = 0; j < kolom; j++) {
            if (i > j) {
                result[i][j] = 0;
            }


        }
        return result;
    }
}

The output that I get is simply the matrix itself which is not what I need.

{{10,11,12},{13,14,15},{16,17,18}}
{{1,2,3},{4,5,6},{7,8,9}}
{{1,2},{3,4}}

The output I need would be:

{{10,11,12},{0,14,15},{0,0,18}}
{{1,2,3},{0,5,6},{0,0,9}}
{{1,2},{0,4}}

You simply have return result; in the wrong place. Like this

vector<vector <int>> upper_triangle(vector<vector <int>> n) {
    int rij = n.size();
    int kolom = n.size();
    vector<vector<int>> result = n;
    for (int i = 0; i < rij; i++) {
        ...
    }
    return result;
}

not this

vector<vector <int>> upper_triangle(vector<vector <int>> n) {
    int rij = n.size();
    int kolom = n.size();
    vector<vector<int>> result = n;
    for (int i = 0; i < rij; i++) {
        ...
        return result;
    }
}

Of course the point of indenting code is to make errors like this easier to spot.

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