我正在寻找一种在C ++中混乱std :: map的方法。我有一个std :: map,键作为整数,值作为struct,我想要随机键。我试图使用std :: random_shuffle,但它没有编译。所以我创建了一个临时向量,我填充了这个向量,将其洗牌并用它来交换地图。
这就是我目前的做法:
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <ctime>
#include <cstdlib>
std::vector<int> temp_vec_registration;
int myrandom(int i) { return std::rand()%i; }
struct CRegInfo
{
bool success;
int num_order;
int type;
CRegInfo(bool succ, int num, int type)
: success(succ), num_order(num), type(type)
{}
};
typedef std::map<int, CRegInfo> RegInfo;
RegInfo register_chars;
int main()
{
std::srand(unsigned(std::time(0)));
temp_vec_registration.clear();
register_chars.clear();
for (int i = 0; i <= 10; i++)
temp_vec_registration.push_back(i);
std::random_shuffle(temp_vec_registration.begin(), temp_vec_registration.end(), myrandom);
for (std::vector<int>::iterator it1=temp_vec_registration.begin(); it1!=temp_vec_registration.end(); ++it1)
register_chars.insert(RegInfo::value_type(*it1, CRegInfo(false, 0, 0)));
for (auto it2 = register_chars.begin(); it2 != register_chars.end(); ++it2)
std::cout << it2->first << "\t";
}
但它不起作用,矢量具有随机数,但地图在键中始终具有相同的数字。 (0,1,2,3 ...... 10)。
嗯,虽然这在技术上可能有一些额外的黑客攻击,但是采用天真的方法 - std::map
是一个有序的存储,即它保持其密钥之间的排序,这是其主要特征,对于简单操作的对数复杂性的代价。
std::unordered::map
,顾名思义,并没有提供这样的保证,所以你可以尝试用unordered_map
做同样的运气......如果你只是想以不确定的顺序迭代地图项目,那么,使用你的洗牌矢量吧。