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

时间:2015-10-28 04:06:29

标签: c++ arrays bit-shift

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

到目前为止,我还没有运气在我希望修改的数组的内存位置上使用shift运算符。我以为我能够将所有值放在一个新数组中,然后交换位于这些地址的第一个和最后一个值,然后我将移动最后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;
}

1 个答案:

答案 0 :(得分:3)

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,