出于某些奇怪的原因,我有一项任务是使用 C++ 标准库中提供的 shuffle 或 random_shuffle 函数 随机播放 vector 的内容。以下是一些具有(非功能性)功能的基本代码来完成这项工作,让您更清楚地了解我的意思:
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
我想这样做的方式是:
- “push_back” vector 以创建一个临时点
- 随机分配一个索引到临时点
- 随机分配一个索引到新的空位
- 将临时点的索引放入最后剩下的空索引中
- 将 vector “pop_back”到它的原始大小
(就像在数组中切换索引一样)
我不知 Prop 体如何执行此操作,但更重要的是,我不知道这是否可行,或者它是否是执行此操作的最佳方式。你会怎么做?
最佳答案
砰!这实际上很有趣!
我使用 rand 和一个迭代 100 次的“for”循环来随机化它。我还添加了一个“临时”索引,该索引在改组完成后被删除。
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
for (int i = 0; i < 100; i++)
{
int randomIndex = rand() % names.size();
int randomIndex2 = rand() % names.size();
if (randomIndex2 == randomIndex) // make sure the two random values aren't the same
{
do {
randomIndex2 = rand() % names.size();
} while (randomIndex2 == randomIndex);
}
names.push_back("temporary"); // create temporary index at the end of the vector
int last_index_number = (names.size() - 1);
names[last_index_number] = names[randomIndex];
names[randomIndex] = names[randomIndex2];
names[randomIndex2] = names[last_index_number];
names.pop_back(); // bring vector back to original size
}
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
关于C++ 如何在不使用标准库中的洗牌函数的情况下洗牌 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646242/