C语言 你如何交换矩阵中的两行(在 C 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3550475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:16:25  来源:igfitidea点击:

how do you swap two rows in a matrix (in C)?

cmatrixrowswap

提问by user420360

for example, given a matrix:

例如,给定一个矩阵:

1 2 3

1 2 3

4 5 6

4 5 6

7 8 9

7 8 9

if you are goint to swap row[0] and row[1], resulting matrix would be:

如果要交换 row[0] 和 row[1],结果矩阵将为:

4 5 6

4 5 6

1 2 3

1 2 3

7 8 9

7 8 9

can you guys help me get a code in C for this?

你们能帮我得到一个 C 代码吗?

回答by dmckee --- ex-moderator kitten

The answer depends entirely on how your "matrix" is implemented, because the c language has no notion of such a thing.

答案完全取决于您的“矩阵”是如何实现的,因为 c 语言没有这样的概念。

Are you using two dimensional arrays?

你在使用二维数组吗?

double m[3][3];

Or something else?

或者是其他东西?

Two dimensional arrays

二维数组

You will have to move individual elements by hand.

您必须手动移动单个元素。

for (i=0; i<ROWLENGTH; ++i){
  double temp;
  temp = m[r2][i];
  m[r2][i] = m[r1][i];
  m[r1][i] = temp;
}

(here r1and r2are ints that have been set to the two row you want to swap) or see James' memcpyimplementationwhich may well be faster but requires a whole rows worth of temporary memeory.

(这里r1r2是已被设置为你希望两个排掉整数)或看到詹姆斯的memcpy执行这很可能会更快,但需要一个完整行价值的临时memeory的。

Ragged Arrays

参差不齐的数组

If this operation is very common and profiling reveals that it is consuming a lot of time, you might consider using a ragged array implementation of the matrix. Something like this:

如果此操作非常常见并且分析表明它消耗了大量时间,则您可以考虑使用矩阵的不规则数组实现。像这样的东西:

double **m;
m = malloc(sizeof(double*)*NUMROWS);
/* put error checking here */
for (i=0; i<NUMROWS; ++i){
  m[i] = malloc(sizeof(double)*ROWLENGTH);
  /* error checking again */
}

The fun part about this structure is that you can still access it with the [][]notation, but the row swap operation becomes

这个结构有趣的部分是你仍然可以用[][]符号访问它,但是行交换操作变成了

double *temp;
temp = m[r2];
m[r2] = m[r1];
m[r1] = temp;

Ragged arrays have two disadvantages from your point of view (well, three 'cause of the memory management hassle): they require extra storage for the row pointers, and you can't use inline initialization.

从您的角度来看,参差不齐的数组有两个缺点(嗯,三个原因是内存管理麻烦):它们需要额外的行指针存储空间,并且您不能使用内联初始化。

Row-as-astructure

行即结构

C does not support array assignments of the form;

C 不支持表单的数组赋值;

double r[3], q[3] = { 1, 2, 3 };
r = q; /* ERROR */

but it doessupport by-value assignment semantics for structures. Which gives you the implementation that several people have suggested without explaining:

但它确实支持结构的按值赋值语义。这为您提供了几个人建议的实现而无需解释:

typedef struct { double r[ROWLENGTH] } row;
row m[NUMROWS] = { {1, 2, 3}, {4, 5, 6}, {7, 8 9}};

row temp = m[2];
m[2] = m[1];
m[1] = temp;

which is slick. It requires a whole row of memory, but if the compiler is any good is probably fast. The big disadvantage is that you can not address individual matrix elements with the [][]syntax anymore. Rather you write m[i].r[j];

这是光滑的。它需要一整行内存,但如果编译器好的话可能很快。最大的缺点是您不能再使用[][]语法处理单个矩阵元素。而是你写m[i].r[j];

Others

其他

There are many, many other ways to implement a "matrix" in c, but they are mostly much more complicated and useful only in specialized situations. By the time you need them you'll be able to answer this questions for yourself in the context of each one.

有很多很多其他方法可以在 c 中实现“矩阵”,但它们大多更复杂,仅在特殊情况下才有用。当您需要它们时,您将能够在每个问题的上下文中为自己回答这些问题。

回答by James Curran

typedef int Row[3];
Row Matrix[3];

Row Temp;

memcpy(Temp, Matrix[0], sizeof(Row));
memcpy(Matrix[0], Matrix[1], sizeof(Row));
memcpy(Matrix[1], Temp, sizeof(Row));

回答by Jerry Coffin

I'd probably swap one element at a time to avoid using a lot of extra storage. If you're working primarily with things like graphics transforms where the matrices are typically 3x3 or 4x4, James Curran's approach is probablya bit better. If you are (or might be) working with really large matrices, this will save memory, and quite possibly run faster:

我可能会一次交换一个元素以避免使用大量额外的存储空间。如果您主要处理诸如矩阵通常为 3x3 或 4x4 的图形变换之类的事情,那么 James Curran 的方法可能会更好一些。如果您正在(或可能正在)处理非常大的矩阵,这将节省内存,并且很可能运行得更快:

int x[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

for (int i=0; i<3; i++) {
    int temp = x[0][i];
    x[0][i] = x[1][i];
    x[1][i] = temp;
}

回答by user411313

solve this your homework?

解决这个你的作业?

typedef struct {int m[3];} Row;
typedef int RowAccess[3];

main()
{
  Row tmp,row[]={{1,2,3},{4,5,6},{7,8,9}};
  RowAccess *rowa=row;
  tmp=row[0];
  row[0]=row[1];
  row[1]=tmp;
  /* easy access to matrix here: (is this what you want?) */
  rowa[0][0]=0;
  rowa[0][1]=1;
  ...
  return 0;
}

回答by Dan

Hy! this is my first post on stack overflow, I know it's pretty long, hope I won't get banned!

嗨!这是我关于堆栈溢出的第一篇文章,我知道它很长,希望我不会被禁止!

Probably one of the most elegant approaches would be using a function that swaps the two received arguments - using it to swap matrix components. Let's say somethig like swap(a,b). As many have already said, we should consider using a auxiliary variable

可能最优雅的方法之一是使用一个函数来交换两个接收到的参数——使用它来交换矩阵组件。让我们说像swap(a,b) 这样的东西。正如许多人已经说过的,我们应该考虑使用辅助变量

auxiliary = a ;
a = b ;
b = auxiliary ; 

Recently, I picked up a new method, which I found impressing, using bitwise XOR operation (http://en.wikipedia.org/wiki/Xor) thus a auxiliary is not needed

最近,我找到了一种令人印象深刻的新方法,它使用按位异或运算(http://en.wikipedia.org/wiki/Xor),因此不需要辅助

 a ^= b ;
 b ^= a ;
 a ^= b ;

You can easily use this operation to swap two elements ( a and b ) - I belive this is off topic, but I insisted on this idea because I found it pretty interesting. Finally, answering your question, you could use let's say

您可以轻松地使用此操作来交换两个元素( a 和 b )——我认为这与主题无关,但我坚持这个想法,因为我发现它很有趣。最后,回答你的问题,你可以使用让我们说

int swap (int *a , int *b){
    (*a)^=(*b);
    (*b)^=(*a);
    (*a)^=(*b);
    return 0; 
}

while having a matrix declared as

同时将矩阵声明为

#define ROW_COUNT 5
#define COLUMN_COUNT 5
....
int a[ROW_COUNT][COLUMN_COUNT];

You can use your the XOR way the swap the rows, firstly identifyng the elements needed to be swapped ( according to row index, as you already said )

您可以使用 XOR 方式交换行,首先确定需要交换的元素(根据行索引,正如您已经说过的)

printf("\nSwap Row: "); scanf("%d", &swp1) ; // first row index
printf("With Row: "); scanf("%d", &swp2);    // second row index

for (j = 0 ; j < COLUMN_COUNT ; j++){
     swap(  &a[swp1][j] , &a[swp2][j] );   
}

I hope this will be usefull in your further practice.

我希望这对您进一步的实践有用。

Also try this example, I'm sure you'll understand the whole idea much better afterwards (don't forget matrix index starts at 0 !)

也试试这个例子,我相信你之后会更好地理解整个想法(不要忘记矩阵索引从 0 开始!)

#include "stdio.h"
#include "conio.h"

#define ROW_COUNT 5
#define COLUMN_COUNT 5



int swap (int *a , int *b){
        (*a)^=(*b);
        (*b)^=(*a);
        (*a)^=(*b);
        return 0; 

}        

int main(){
    int i, j ;
    int swp1, swp2 ; 
    int a[ROW_COUNT][COLUMN_COUNT];

    // Create ( ROW_COUNT X COLUMN_COUNT ) random matrix

    for (i = 0 ; i < ROW_COUNT ; i++ ) 
        for (j = 0 ; j < COLUMN_COUNT ; j++ )  a[i][j] = rand();

    // Display matrix before row swap

    for (i = 0 ; i < ROW_COUNT ; i++ ){ 
        for (j = 0 ; j < COLUMN_COUNT ; j++ )  printf("%d\t",a[i][j]);
        printf("\n");     
    }

    // Elements to be swapped

    printf("\nSwap Row: "); scanf("%d", &swp1) ;  // first row index
    printf("With Row: "); scanf("%d", &swp2);     // second row index

    // Swapping right here

    for (j = 0 ; j < COLUMN_COUNT ; j++){
         swap(  &a[swp1][j] , &a[swp2][j] );   
    }


    // Display once again   

    printf("\n");
    for (i = 0 ; i < ROW_COUNT ; i++ ){ 
        for (j = 0 ; j < COLUMN_COUNT ; j++ )  printf("%d\t",a[i][j]);
        printf("\n");     
    }   



    getch();            
 return 0;   
} 

回答by Beerfazz

There is a function called swap:

有一个名为swap的函数:

#include <algorithm>
int A[][] = {{1,2,3},{4,5,6},{7,8,9}};
swap(A[0],A[2]); //swaps first and last row

回答by dash-tom-bang

temprow = row[1];
row[1] = row[0];
row[0] = temprow;