c++ - 如何随机洗牌 map 中的值?

标签 c++ algorithm map stl shuffle

我有一个 std::map,键和值都是整数。现在我想随机打乱 map ,所以键随机指向不同的值。我试过 random_shuffle 但它没有编译。请注意,我并不是要随机播放键,这对 map 来说毫无意义。我正在尝试随机化这些值。

我可以将这些值放入一个 vector 中,将其打乱,然后再复制回去。有没有更好的办法?

最佳答案

您可以将所有键放入 vector 中,打乱 vector 并使用它来交换 map 中的值。

这是一个例子:

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <random>
#include <ctime>

using namespace std;
int myrandom (int i) { return std::rand()%i;}
int main ()
{
    srand(time(0));
    map<int,string> m;
    vector<int> v;
    for(int i=0; i<10; i++)
        m.insert(pair<int,string>(i,("v"+to_string(i))));

    for(auto i: m)
    {
        cout << i.first << ":" << i.second << endl;
        v.push_back(i.first);
    }
    random_shuffle(v.begin(), v.end(),myrandom);
    vector<int>::iterator it=v.begin();
    cout << endl;
    for(auto& i:m)
    {
        string ts=i.second;
        i.second=m[*it];
        m[*it]=ts;
        it++;
    }
    for(auto i: m)
    {
        cout << i.first << ":" << i.second << endl;
    }
    return 0;
}

关于c++ - 如何随机洗牌 map 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16068927/

相关文章:

java - List<Map<String,Object>> 到 org.json.JSONObject?

java - 根据值对 Map<Key,Value> 进行降序排序

c++ - 真正的 fft 错误 - ffmpeg

c++ - 如何在工作线程(非 UI 线程)中创建模态对话框?

php - 如何从其他关联数组创建关联数组?

python - 反规范化单位向量

c++ - 将 fpos_t 转换为 int 或 char

c++ - 释放内存(如果可能)

python - 找出不满足条件的最小非负整数

java - 在嵌套数据结构上使用 Java8 流创建 map