c++ - 交换数组中的元素以反转数组

标签 c++ arrays swap

我得到了一个在 C++ 中反转动态数组的作业。到目前为止,从我的逻辑来看,我正在考虑循环遍历数组来反转它。这是我的代码:

int main ()
{
    const int size = 10;
    int num_array[size];

    srand (time(NULL));

    for (int count = 0; count< sizeof(num_array)/sizeof(num_array[0]) ; count++){
        /* generate secret number between 1 and 100: */
        num_array[count] = rand() % 100 + 1;
        cout << num_array[count] << " " ;
    }

    reverse(num_array[size],size);

    cout << endl;

    system("PAUSE");
    return 0;
}

void reverse(int num_array[], int size)
{
    for (int count =0; count< sizeof(num_array)/sizeof(num_array[0]); count++){
        cout << num_array[sizeof(num_array)/sizeof(num_array[0])-1-count] << " " ;
    }

    return;
}

不知怎的,我认为我的逻辑在那里,但这段代码不起作用,有一些错误。然而,我的老师告诉我,这不是问题想要的方式。这是问题:

    Write a function reverse that reverses the sequence of elements in an array. For example, if reverse is called with an array containing 1 4 9 16 9 7 4 9 11,
then the array is changed to 11 9 4 7 9 16 9 4 1.

到目前为止,她用相反的方法告诉我们,你需要交换数组元素。所以这是我的问题如何交换数组元素以使输入的数组反转

提前致谢。

更新部分

    int main ()
{
const int size = 10;
int num_array[size];

srand (time(NULL));

for (int count = 0; count< size ; count++){
    /* generate secret number between 1 and 100: */
    num_array[count] = rand() % 100 + 1;
    cout << num_array[count] << " " ;
}

reverse(num_array,size);

cout << endl;

system("PAUSE");
return 0;

}

void reverse(int num_array[], const int& size)
{
for (int count =0; count< size/2; count++){
    int first = num_array[0];
    int last = num_array[count-1];
    int temp = first;
    first = last;
    last = temp;
}

}

最佳答案

您的reverse函数应如下所示:

void reverse(int* array, const size_t size)
{
    for (size_t i = 0; i < size / 2; i++)
    {
        // Do stuff...
    }
}

并称其为:

reverse(num_array, size);

关于c++ - 交换数组中的元素以反转数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16356183/

相关文章:

c++ - 错误 c2338 C++ 标准不提供此类型的散列

c++ - 如何在 OSX 上为 ncurses 提供鼠标支持?

c++ - curllib POST 正文数据(如何?)

c++ - 在 C++ 中连接 3 个或更多元素的字符串 (string[i]+string[i+1]+string[i+2])

c - 匹配两个数组的有效方法

c++ - 我想计算 char* word_list[] (C++) 中的字符串数量

c - 使用 XOR 交换两个指针

java - 如何使用不同的数据类型进行交换

c - 为什么不打印数组?

java - 如何将数组列表中的特定项目移动到第一项