Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

c++ - C ++:交换矩阵的行:使用单维数组(C++: Swap Rows For A Matrix: Using a SINGLE DIMENSION Array)

Dear nice and smart people, would you mind sharing with me why my code is unable to swap rows for a matrix please?

(亲爱的聪明人,您能否与我分享为什么我的代码无法将行交换为矩阵的原因?)

When I run the code, both rows become the same, omg.

(当我运行代码时,两行都变为相同,omg。)

entries[i] is the dynamic array storing the elements in the matrix.

(entry [i]是在矩阵中存储元素的动态数组。)

Elements are stored row by row, from left to right.

(元素从左到右逐行存储。)

ie in a 3X3 matrix, entries[2] is 3rd element on the 1st row, entries[3] is 1st element on the 2nd row

(也就是说,在3X3矩阵中,entries [2]是第一行的第3个元素,entries [3]是第二行的第一个元素)

n = number of rows in matrix
m = number of columns in matrix

void Matrix::SwapRows(int i, int j) {
    double* temp;
    temp = new double[n * m];
    double* temp2;
    temp2 = new double[n * m];
    for (int a = 1; a <= n; a++) {
        for (int b = 1; b <= m; b++) {
            if (a == i) {
                temp[(j - 1) * m + b - 1] = entries[(j - 1) * m + b - 1];
                entries[(a - 1) * m + b - 1] = temp[(j - 1) * m + b - 1];
            }
            if (a == j) {
                temp2[(i - 1) * m + b - 1] = entries[(i - 1) * m + b - 1];
                entries[(a - 1) * m + b - 1] = temp2[(i - 1) * m + b - 1];
            }
        }
    }
    delete temp;
    delete temp2;
}
  ask by Chen JG Thomas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...