如何在C++中随机排列指针列表
How to shuffle list of pointers in C++?
如何在C++中洗牌 stl 指针列表?我在类播放器上有指针的 stl 向量,我像洗牌一样
std::random_shuffle(players.begin(), players.end());
是否已经有不需要随机访问的随机列表算法,或者我需要将列表转换为矢量 => 洗牌 => 回到列表?有没有更优雅的解决方案?
随机随机随机算法将特定元素与随机选择的元素交换。重复遍历列表以获取元素的效率非常低(即这将是一个O(n^2)
操作)。
这就是为什么最好(更快)将列表复制到数组一次,进行随机洗牌并可能恢复列表的原因。那将是3*n
遍历,这仍然是O(n)
.
std::random_shuffle
需要一个随机迭代器。矢量支持此功能,而列表不支持。怎么样std::deque
,它就像一种向量和列表。
你的问题很有趣。所以,我试着写一些东西,最后想出了这个。
//---------- sample List initialization ------
list<string> lst;
lst.push_back("A");
lst.push_back("B");
....
lst.push_back("Y");
lst.push_back("Z");
#define LIST_SIZE 26
//--------------------------------------------
//------------- Shuffle Algorithm ------------
unordered_multimap<int,string> mymap;
int HashKeys[LIST_SIZE];
srand((int)time(NULL) * (int)clock());
for(int i = 0; i<LIST_SIZE; i++) // loop 'n' times
{
HashKeys[i] = rand(); // O(c) operation
}
for(int i = 0;lst.size() > 0; i++) // loop 'n' times
{
// O(n) operation ( varies from O(c) to O(n) according to the situations )
mymap.insert(std::make_pair<int,string>(HashKeys[rand() % LIST_SIZE],lst.front()));
lst.pop_front(); // O(c) operation
}
unordered_multimap<int,string>::iterator it;
for(int i = 0; i < LIST_SIZE ;i++) // loop 'n' times
{
while(mymap.count(HashKeys[i]) > 0) // unpredictable
{
it = mymap.find(HashKeys[i]); // O(c) for single O(n) for multi
// ...USAGE...
cout << it->second << endl;
lst.push_back(it->second);
//............
mymap.erase(it); // O(c) operation
}
}
//-------------------------------------------------
如果哈希映射中同一键有多个值,则时间复杂度为 O(n^2)。否则,时间复杂度为 O(n)。所以一切都取决于功能(rand() % LIST_SIZE)
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 为什么不;名字在地图上是按顺序排列的吗
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 使用指针重新排列数组中的数字
- C 按顺序排列一个指针阵列
- 如何在C++中随机排列指针列表