随机化/修改数组

时间:2014-10-26 23:52:33

标签: c++ arrays random

所以我试图随机化一个1,2,3,4,5,6,7,8,9,10的数组。然后要求用户选择数组中的位置,然后修改它。之后,它应显示用户为10个值的全部输入的数字。最后,它需要获得随机化的原始数组并将其反转。

到目前为止,我有这个

#include <iostream>

using namespace std;
int array [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rarray [10];

int main() {
    cout << "Random Array = ";
    for (int i = 0; i < 10; i++) {
        int index = rand() % 10;

        int temp = array[i];
        array[i] = array[index];
        array[index] = temp;
    }

    for (int i = 1; i <= 10; i++) {
        cout << array[i] << " "; //somehow, this display needs to be entered into another array
    }

    system("PAUSE");
}

但正如评论中所述,我坚持认为如何做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以使用C ++标准库中的std::shufflestd::copystd::reverse来完成此操作。

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int position;

    // Get the position to modify and make sure it's within our bounds.
    do
    {
        cout << "Select a position: ";
    }
    while (!(cin >> position) || position < 0 || position > 9);

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

    //  Shuffle the array. We use std::begin and std::end to get the bounds of
    //  of the array instead of guessing it's size.
    std::random_shuffle(std::begin(array), std::end(array));

    //  Copy it to the new array
    std::copy(std::begin(array), std::end(array), rarray);

    //  Modify the new array and display it. Add your own code here to get the
    //  value it is modified with.
    rarray[position] = 100;

    for (auto value : rarray)
        cout << value << " ";
    cout << endl;

    //  Reverse the original array and display it
    std::reverse(std::begin(array), std::end(array));

    for (auto value : array)
        cout << value << " ";
    cout << endl;

    system("PAUSE");
}

或者如果您不允许使用C ++标准库,则需要手动处理所有内容。这是一项繁琐的任务,但却是为什么应尽可能利用C ++标准库的一个很好的例子。这也更容易出错,更难维护,难看。

int main()
{
    int position;

    do
    {
        cout << "Select a position: ";
    } while (!(cin >> position) || position < 0 || position > 9);

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

    for (int i = 0; i < 10; i++)
    {
        int index = rand() % 10;

        int temp = array[i];
        array[i] = array[index];
        array[index] = temp;
    }

    //  Copy the array
    int rarray[10];
    for (int i = 0; i < 10; i++)
    {
        rarray[i] = array[i];
    }

    //  Modify the new array and display it
    rarray[position] = 100;
    for (int i = 0; i < 10; i++)
    {
        cout << rarray[i] << " ";
    }
    cout << endl;

    //  Reverse the old array and display it
    for (int i = 0; i < 10 / 2; i++)
    {
        int tmp = array[i];
        array[i] = array[9 - i];
        array[9 - i] = tmp;
    }
    for (int i = 0; i < 10; i++)
    {
        cout << array[i] << " ";
    }
    cout << endl;

    system("PAUSE");
}

这两种实现都接近您的原始请求,但您可能需要稍微扩展它以完全符合您的要求。他们应该让你顺利地前进。