如何随机化一个充满字符串的数组? C ++

时间:2012-10-20 04:19:52

标签: c++ arrays

我搜索并发现一些随机数字,但我不认为它适用于字符串....例如我在数组中有这样的列表:

string restaurants[] = {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};

我如何随机化这个或者只是将它们全部交换并混淆它们?

3 个答案:

答案 0 :(得分:4)

如果你不需要,不要重新发明轮子。

std::random_shuffle(std::begin(restaurants), std::end(restaurants));

在C ++ 03中,没有实现自己的beginend

std::random_shuffle(restaurants, restaurants + sizeof restaurants / sizeof restaurants[0]);

请注意,除非您使用诸如std::vector之类的内容,否则将其传递给函数以通过引用执行此操作将需要使用后者并使用其他大小参数。

答案 1 :(得分:1)

你可以这样做

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

int main ()
{
  static string numbers[] =  {"Texas Roadhouse,","On The Border,","Olive Garden,","Panda       Express,","Cracker Barrel,","IHOP,","Panda Express,","Pei Wei"};
  srand(time(0));
  int rand_index = rand() % 10;
  cout << numbers[rand_index] << endl;

  string input;
  getline(cin,input);
  cout << (((input=="even")==(rand_index+1)%2==0) ? "Right." : "Wrong.") << endl;
}

答案 2 :(得分:0)

只是一种有趣的选择(按随机排序):

std::sort(restaurants, restaurants + sizeof(restaurants) / sizeof(std::string), [](int x, int y) -> bool { return rand() % 100 >= 50; });