所以我编写了一些代码来随机访问向量的5个位置。 我通过从文件中填充一个向量,然后创建第二个向量来保存第一个
的随机5个元素来完成此操作从文件填充第一个向量
std::vector<std::string> ElemAlg::GetQuiz(int quizNo)
{
std::ifstream fin("1.txt");
while (std::getline(fin, question))
{
questions.push_back(question);
}
return questions;
}
从第一个向量中访问5个随机元素并将它们复制到新向量
std::vector<std::string> ElemAlg::AllocateQuestions()
{
unsigned int seed = time(0);
std::ifstream infile("rand.txt");
if (infile)
{
infile >> seed;
infile.close();
}
srand(seed);
for (int i = 0; i <= 4; i++)
{
seed = rand();
unsigned int randomIndex = seed % questions.size();
selectedQuestions.push_back(questions[randomIndex]);
}
std::ofstream outfile("rand.txt");
outfile << seed;
outfile.close();
return selectedQuestions;
}
这是一个相对有效的方法,我需要2个向量吗?或者我是否完全复杂化了一个简单的问题?
有没有办法测试它的效率?
感谢任何人的时间。 (注意我知道randomIndex的重复是可能的)