在一个for循环中显示2个迭代的数组

时间:2016-03-29 10:13:04

标签: c++ c++11

我正在努力创建一个测试的模拟 1.随机选择多项选择答案 2.显示a)b)c)d)

中的选项

我有两个代码单独完成但是我可以使用for循环来显示这个吗?这是最好的方法吗?感谢所有帮助!

#include <iostream>
#include <ctime> 
#include <cstdlib>
using namespace std;

int main (){
const int TEST_SIZE = 13;
srand(time(0));
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };

for (int i = 0; i < TEST_SIZE; i++){
    //generate random index number (0,1,2,3,4,5...)
    int index = rand() % FACE_SIZE;

    //swap animals[i] with animals[index]
    string temp = animals[i];
    animals[i] = animals[index];
    animals[index] = temp;

}
//loop through array and print values
for (int i = 0; i < 7; i++){
    cout << animals[i] << "  ";
}

}

//第2部分的单独代码:来自a-g的选择

#include <iostream>
#include <string>
using namespace std;

int main()
{
const int CHOICE_SIZE = 7;
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
for (int i = 0; i < CHOICE_SIZE; i++) {
cout << choices[i] << "  ";
}
}

1 个答案:

答案 0 :(得分:0)

您可以迭代两个数组,并在较小的数据结束时停止

#include <iostream>
#include <ctime> 
#include <cstdlib>
using namespace std;

int main (){
    const int TEST_SIZE = 13;
    srand(time(0));
    string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" };

    for (int i = 0; i < TEST_SIZE; i++){
        //generate random index number (0,1,2,3,4,5...)
        int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE?

        //swap animals[i] with animals[index]
        string temp = animals[i];
        animals[i] = animals[index];
        animals[index] = temp;

    }
    //loop through array and print values
    for (int i = 0; i < 7; i++){
        cout << animals[i] << "  ";
    }

    const int CHOICE_SIZE = 7;
    string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" };
    for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) {
        cout << choices[i] << "  " << animals[i] << ", ";
    }
}

另外,请考虑如果要使用固定大小的数组,可以使用std :: array:

#include <array>
std::array<string, TEST_SIZE> animals = {...};

为了改组你可以使用&#39;算法&#39;中的std :: shuffle。标题。