在 C++ 中为列交换行 [英] Swap Rows for Columns in C++

查看:18
本文介绍了在 C++ 中为列交换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试逐列更改行时遇到了一些问题.

I am having some trouble trying to change rows by columns.

我想要的只是更改静态二维数组 (3x3) 的行和列.我不想只是简单地打印带有反向索引的数组.我试图将数组中实际位置的值存储在 int aux 中,但没有效果.

All I want is change rows and columns of a static 2D array (3x3). I don't want to just simply print the array with reverse indexes. I tried to store the value of the actual position in the array in int aux but there is no effect.

输入:

1 2 3 
4 5 6
7 8 9

输出:

1 4 7
2 5 8
3 6 9

使用此代码,结果是相同的二维数组.我看不到问题,你能帮我吗?

With this code, the result is the same 2D array. I can't see the problem, can you help me?

#include <iostream>

using namespace std; 

int main ()
{
    int vec[3][3];
    int x, y, aux;
//Input
    for(x=0; x<3;x++)
{
    for(y=0; y<3;y++)
    {
    cout << "POSITION ["<<x+1<<"]["<<y+1<<"]: ";
    cin >> vec[x][y];
    }
}

    cout<<"\nPress ENTER...";
    cin.ignore();
    cin.get();
    system("CLS");
//Array before the change
cout<<"ARRAY A"<<endl;
for(x=0; x<3;x++)
{
    for(y=0; y<3;y++)
    {
    cout<<vec[x][y]<<"\t";
    }
cout << "\n";
}
//Change
for(x=0; x<3;x++)
{
    for(y=0; y<3;y++)
    {
        if(x!=y)
        {
            aux=vec[x][y];
            vec[x][y]=vec[y][x];
            vec[y][x]=aux;
        }
    }
}

//Array after the change
cout<<"\nARRAY A"<<endl;
for(x=0; x<3;x++)
{
    for(y=0; y<3;y++)
    {
    cout<<vec[x][y]<<"\t";
    }
cout << "\n";
}
cout << "\n";
system("PAUSE");
return 0;
}

推荐答案

您要交换元素两次.于是他们又回到了原来的地方.

You are swapping the elements twice. Hence they come back to their original place.

改变

if(x!=y)

if(x < y)

所以只有当元素是 (2,3) 时才交换.如果是(3,2),那么它已经被交换了,我们不应该再交换它.

So swap only if the element is say (2,3). If it is (3,2), then it is already swapped and we should not swap it again.

这篇关于在 C++ 中为列交换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆