如何使用字符串随机数组?

时间:2013-01-01 08:37:10

标签: c++ arrays

我希望这是一个非常简单的问题,但是如何在数组中随机输入一个字符串

例如,对于vaules,这样做

`

#include <cstdlib> 
#include <iostream>
using namespace std;
int main() 
{
srand ( time(NULL) ); //initialize the random seed


const char arrayNum[4] = {'1', '3', '7', '9'};

int RandIndex = rand() % 4;
int RandIndex_2 = rand() % 4;
int RandIndex_3 = rand() % 4;
int RandIndex_4 = rand() % 4; //generates a random number between 0 and 3

cout << arrayNum[RandIndex] << endl;;
system("PAUSE");
return 0;
}    `

如果arraynum中有字符串

,我该如何应用呢?

虽然我已经在我的搜索中遇到过这样的问题

std::string textArray[4] = {"Cake", "Toast", "Butter", "Jelly"};

但我遇到的只是一个十六进制的答案,它本身并没有改变。因此,我认为它可能甚至不是随机的。

1 个答案:

答案 0 :(得分:5)

您可以使用std::random_shuffle

#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

int main() {
    std::srand(std::time(0));
    std::string str = "123456212";
    std::random_shuffle(str.begin(),str.end());
    std::cout << str;
}

可能的输出:412536212

如果您正在使用C ++ 11,您可以对C样式数组执行相同的操作:

int main() {
    std::srand(std::time(0));
    std::string str[4] = {"Cake", "Toast", "Butter", "Jelly"};
    std::random_shuffle(std::begin(str),std::end(str));
    for(auto& i : str)
        std::cout << i << '\n';
}

或者如果您缺少C ++ 11编译器,您可以选择其他方法:

int main() {
    std::srand(std::time(0));
    std::string str[4] = {"Cake", "Toast", "Butter", "Jelly"};
    std::random_shuffle(str, str + sizeof(str)/sizeof(str[0]));
    for(size_t i = 0; i < 4; ++i) 
        std::cout << str[i] << '\n';
}