如何在C ++中创建列表或数组,然后将这些对象随机分配给另一个变量?

时间:2015-09-13 18:02:55

标签: c++ arrays list

如果使用其中任何一种方法,我真的不确定应该使用哪种方法。但下面是关于汽车通过红绿灯的剧本。一旦一定数量的汽车通过,灯光将从绿色变为黄色,黄色变为红色。

要为汽车添加一些功能,我想为它们分配4种颜色中的一种。我创建了一个数组,但是当我运行程序时,看起来它将数组分配给我的输出而不是颜色,它为每个" car"添加了一个奇怪的代码。

如果这不是解决这个问题的方法,那会是更好的方法吗?

#include <iostream>
#include <string>
#include <windows.h> //Allow to import Sleep()
using namespace std;

void main()

{
    int cars = 0;
    string go, light;
    string testArray[4] = { "Red", "Green", "Blue", "White" }; //Car colors to assign to cars passing

    cout << "The light is green \n"
        << "Type go and press enter to start cars" << endl;
    cin >> go;
    cout << "Cars that have passed the light. \n";

    do
    {
        cout << cars << " " << testArray << endl;
        cars++;
        Sleep(1000); //Delay output for 1 second
    } while (cars < 6);
    {

        cout << "Yellow light" << endl;
        cout << "There are " << cars + 10 << " cars slowing down." << endl; //cars + 10 cars slowing down on yellow light.
    }

    cout << "The light is red. There are " << cars << " cars stopped.\n";

}

输出低于

The light is green
Type go and press enter to start cars
go
Cars that have passed the light.
0 007CF72C
1 007CF72C
2 007CF72C
3 007CF72C
4 007CF72C
5 007CF72C
Yellow light
There are 16 cars slowing down.
The light is red. There are 6 cars stopped.
Press any key to continue . . .

2 个答案:

答案 0 :(得分:0)

创建一个保存颜色索引的整数。

int color_index;
do
    {
        color_index=rand()%4;
        cout << cars << " " << testArray[color_index] << endl;
        cars++;
        Sleep(1000); //Delay output for 1 second
    } while (cars < 6);

你还可以包括&#34; srand(time(NULL));&#34;在main()中确保每次运行程序都会给出不同的随机颜色(不是相同的顺序)。

答案 1 :(得分:0)

您正在打印阵列本身,而不是它的成员,这就是为什么你得到奇怪的数字,所有这些都是内存地址。使用array[index]代替rand() % ARRAY_SIZE等方法获取随机索引。