C ++ - 随机选择字符串而不多次选择它

时间:2013-10-20 06:30:22

标签: c++ string random map

我手上满是各自包含几个字符串的对象。现在它设置为结构,每个结构包含一个带有键1 ... n的映射,每个字符串对应一个(map<int,string> strs),如果存在更好的方法,则可以更改。我需要随机访问所有这些条目而不重叠,并知道我已经完成了。我怎么能用地图或其他数据结构做到这一点?感谢。

2 个答案:

答案 0 :(得分:5)

以下是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;
}

这将采用向量,并以随机顺序返回它的副本。如果你有一个字符串向量,你可以像这样使用它(我在这里使用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;
}

希望这有帮助!

答案 1 :(得分:0)

一个可怕的解决方案,不要这样做。对于大的候选矢量来说非常慢,这具有n平方的复杂性。改组更好,线性复杂。

std::vector<int> RandomThing(int number, int min, int max)
{
    assert(!"RandomThing" && min < max);
    std::vector<int> candidates;
    for(int i=min; i<max; i++)
        candidates.push_back(i);

    std::vector<int> result;
    for(int i=0; i<number;)
    {
        int candidate_index = rand() % candidates.size();
        result.push_back(candidates[candidate_index]);

        std::vector<int>::iterator it = candidates.begin();
        std::advance(it, candidate_index);
        candidates.erase(it);
    }
    return result;
}