gpt4 book ai didi

c++ - 如何使用移位寄存器操作数移位数组的元素?

转载 作者:行者123 更新时间:2023-11-30 02:35:42 28 4
gpt4 key购买 nike

我有一个包含数字的二维数组,我想将其中的所有元素移动一个,并将每行中的最后一个值环绕到第一个元素。例如,包含 1、2、3 的行将换行为 3、1、2。

到目前为止,我还没有在我希望修改的数组的内存位置上使用移位运算符。我认为我可以将所有值放在一个新数组中,然后交换位于这些地址的第一个和最后一个值,然后我将移动最后 8 个值。没有运气。

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int const ROWS = 4;
int const COLS = 9;

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

int shiftTable[ROWS][COLS];


unsigned int num1 = 0;
unsigned int num2 = 0;
unsigned int num3 = 0;
unsigned int num4 = 0;
unsigned int newNum1 = 0;
unsigned int newNum2 = 0;
unsigned int newNum3 = 0;
unsigned int newNum4 = 0;

unsigned concatenate(unsigned, unsigned);

int _tmain(int argc, _TCHAR* argv[])
{

int *ptrTable;
ptrTable = &numberTable[0][0];

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

newNum1 = numberTable[0][i];
newNum2 = numberTable[1][i];
newNum3 = numberTable[2][i];
newNum4 = numberTable[3][i];
num1 = concatenate(num1, newNum1);
for (int j = 0; j < 4; j++){
numberTable[0][i] >>= 1;
cout << "Before table shift: "<<ptrTable << endl;
*ptrTable >>= 1;
cout << "After Table Shift: "<<ptrTable << endl;

}
}
num1 = concatenate(num1, newNum1);
unsigned int *num1ptr;
num1ptr = &num1;
cout << *num1ptr << endl;
*num1ptr >>= 1;
cout << *num1ptr<< endl;
num1 >>= 1;
cout << num1;

getchar();
return 0;
}


unsigned concatenate(unsigned x, unsigned y) {
unsigned pow = 10;
while (y >= pow)
pow *= 10;
return x * pow + y;
}

最佳答案

C++ Shift 运算符的行为与您想象的不同。你实际上应该使用 std::rotate从标准算法库中旋转数组。了解这是如何工作的

示例代码

#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>
int const ROWS = 4;
int const COLS = 9;


int main() {
int numberTable[ROWS][COLS] = {
{1, 2, 3, 4, 5, 6, 7, 8, 9},
{7, 2, 8, 4, 5, 4, 7, 3, 1},
{9, 9, 7, 4, 9, 9, 8, 7, 6},
{6, 3, 7, 4, 5, 4, 5, 7, 9}
};
// std::array<std::array<int, COLS>, ROWS> numberTable = {{
// {1, 2, 3, 4, 5, 6, 7, 8, 9},
// {7, 2, 8, 4, 5, 4, 7, 3, 1},
// {9, 9, 7, 4, 9, 9, 8, 7, 6},
// {6, 3, 7, 4, 5, 4, 5, 7, 9}
// }};
// Left Rotation
for(auto& row: numberTable) {
std::rotate(std::begin(row),std::begin(row) + 1, std::end(row));
}
for(auto& row: numberTable) {
std::copy(std::begin(row),
std::end(row),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << std::endl;
}

return 0;
}

示例输出

2,3,4,5,6,7,8,9,1,
2,8,4,5,4,7,3,1,7,
9,7,4,9,9,8,7,6,9,
3,7,4,5,4,5,7,9,6,

关于c++ - 如何使用移位寄存器操作数移位数组的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33382755/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com