Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

shift cyclically second row in 2D array c++ 98

Hi guys i was looking around some old threads but i can't find anything that works for me. I need to shift second row in my array with cpp 98 from this

int mat[4][4] = {{1, 2, 3, 4}, 
                 {5, 6, 7, 8}, 
                 {9, 10, 11, 12}, 
                 {13, 14, 15, 16}};

to this

int mat[4][4] = {{1, 2, 3, 4}, 
                 {5, 6, 7, 8}, 
                 {12, 9 , 10, 11}, 
                 {13, 14, 15, 16}};

I don't want to print out anything just switching places in array, Thank you

question from:https://stackoverflow.com/questions/65832587/shift-cyclically-second-row-in-2d-array-c-98

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

1 Answer

0 votes
by (71.8m points)

One very easy method is this, first create a temporary array to store the initial values,

int temp[4] = { mat[2][3], mat[2][0], mat[2][1], mat[2][2] };

Then use std::memcpy to copy the data into mat[2],

std::memcpy(mat[2], temp, sizeof(int) * 4);

Bonus: You can use a scope to save some memory. It would be like this,

int mat[4][4] = { {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12},
    {13, 14, 15, 16} };

...

{
    int temp[4] = { mat[2][3], mat[2][0], mat[2][1], mat[2][2] };
    std::memcpy(mat[2], temp, sizeof(int) * 4);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...