简体   繁体   English

交换二维数组中的元素

[英]Swapping elements in 2d array

So, I'm trying to swap the matrix elements with respect to the main diagonal.所以,我试图根据主对角线交换矩阵元素。 I have tried using temp method (switching values while using temp variable), also tried std::swap(a,b) .我尝试过使用临时方法(在使用临时变量时切换值),也尝试过std::swap(a,b) Somehow it only swaps upper right side of the matrix and leaves another half not changed.不知何故,它只交换矩阵的右上方,而另一半没有改变。

在此处输入图片说明

How do I make everything swap?我如何让一切都交换?

My code:我的代码:

#include <iostream>

using namespace std;

int main()
{
    const int n = 7;
    srand (time(NULL));

    int matrix[n][n];

    cout << "Original Matrix :" << endl;

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            (i == j) ?  matrix[i][j] = 0 : matrix[i][j] = rand() % 100+1;
            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }   

    cout << "\nRemade Matrix:" << endl;

    for (int i = 0; i < n; i++)
    {   

        for (int j = 0; j < n; j++)
        {
            int temp = matrix[i][j];
            matrix[i][j] = matrix[j][i];
            matrix[j][i] = temp;


//          swap(matrix[i][j], matrix[j][i]);      //another method

            cout << matrix[i][j] << "\t";
        }
        cout << endl;
    }
    return 0;
}

You are basically swapping them twice, replace your swapping loops with this.你基本上交换了两次,用这个替换你的交换循环。 Notice the condition of the second loop, it's j < i .注意第二个循环的条件,它是j < i Then, you can print it with another set of loops.然后,您可以使用另一组循环打印它。

for (int i = 0; i < n; i++)
    for (int j = 0; j < i ; j++)
        swap(matrix[i][j], matrix[j][i]);

Your logic is almost ok.你的逻辑几乎没问题。 Just the inner loop counter will start from "i+1" else after the swapping the value is again getting overlapped.只有内循环计数器将从“i+1”开始,否则在交换值再次重叠之后。 Try the following code and make sure you understand it.尝试以下代码并确保您理解它。 Happy coding!快乐编码!

for (int i = 0; i < n; i++)
{   

    for (int j = i + 1; j < n; j++)
    {
        int temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
    }

}

for (int i = 0; i < n; i++)
{   
    for (int j = 0; j < n; j++)
    {
        cout << matrix[i][j] << "\t";
    }
    cout << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM