C++ - 随机选择字符串而不选择它超过一次

标签 c++ string random dictionary

我手上满是对象,每个对象都包含几个字符串。现在它被设置为结构,每个结构包含一个映射,键为 1...n,每个字符串一个(map<int,string> strs),如果存在更好的方法,可以更改。我需要在不重叠的情况下随机访问所有这些字符串,并且知道我已经完成了。我怎样才能做到这一点,无论是使用 map 还是其他数据结构?谢谢。

最佳答案

这是 Fisher-Yates shuffle 的一些代码:

template <class T>
std::vector<T> shuffle(std::vector<T> &vect)
{
    std::vector<T> shuffled = vect;
    for(int i = shuffled.size()-1; i >= 1; i--) {
        int idx = rand() % (i+1);
        T tmp = shuffled[idx];
        shuffled[idx] = shuffled[i];
        shuffled[i] = tmp;
    }
    return shuffled;
}

这将接受一个 vector ,并以随机顺序返回它的一个拷贝。如果你有一个字符串 vector ,你可以像这样使用它(我在这里使用 c++11):

int main()
{
    srand(time(NULL));
    std::vector<std::string> strs = {"foo", "bar", "baz", "stack", "overflow"};
    for(auto &str : shuffle(strs)) {
        std::cout << str << std::endl;
    }
    return 0;
}

当然,如果你像我一样懒惰,<algorithm> 中总有 random_shuffle() 函数。 :

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::vector<std::string> strs = {"foo", "bar", "baz", "stack", "overflow"};
    std::random_device rd;
    std::mt19937 g(rd()); // Use a good random number generaor
    std::random_shuffle(strs.begin(), strs.end(), g); // this does the shuffle
    for(auto &str : strs) {
        std::cout << str << std::endl;
    }
    return 0;
}

希望这对您有所帮助!

关于C++ - 随机选择字符串而不选择它超过一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474570/

相关文章:

c++ - 是否可以从 C++ 中的线程返回退出代码?

c++ - 读取包含未知 UTF8 字符串和已知 ASCII 混合的文件

python - 将字符串的所有值更改为某个值

python - python中的随机字节字符串

java - Repaint() 方法不会重新绘制需要的内容

c++ - 在复制构造函数中使用 memcpy 复制 QThread 指针

c++ - 将测试从 GoogleTest 升级到 GoogleMock (Ubuntu 14) 时出现与 pthread 相关的错误

c++ - 如何使用 Boost.Variant 迭代一系列有界类型

c - 如何在c中分割字符串并将每个字符放入数组中?

c - 用随机整数生成数组 C