根据使用次数随机选词

Random word pick based on the number of times that they were used

我有一个像这样的字符串向量:

std::vector<string> words ={"word1", "word2", "word3", "word4"}; //and many more

code 随机化向量(在辅助向量中)并从辅助向量中取出第一个单词。为此,我使用 random_shuffle。到目前为止,一切都很顺利。但是现在,我想尽量减少重复的话。我的想法是将一个词被使用的次数保存在另一个 <int> 向量中,并根据一些权重随机化这些词,这些权重取决于生成器选择一个词的次数。使用次数较多的词具有较低的权重,例如,从未使用过的词具有最大权重(可能 1.0)。 STL 中有什么东西可以做到这一点吗?如果没有,有人可以帮助我完成这项艰巨的任务吗? 任务是:

提前致谢

std::discrete_distribution 可能会有帮助,例如

std::random_device rd;
std::mt19937 gen(rd());

std::vector<std::string> words = {"word1", "word2", "word3", "word4"};
std::vector<std::size_t> weights = {10, 10, 10, 10};

for (int i = 0; i != 12; ++i) {
    std::discrete_distribution<> d(weights.begin(), weights.end());
    
    const auto index = d(gen);
    std::cout << words[index] << std::endl;
    weights[index]--;
}

Demo