查询随机洗牌
Inquiry about random shuffle
昨天我问了一个关于这个的问题,但是由于沟通不周,这个话题被搁置了。所以我试着运行一个程序来洗牌向量中的元素。该部分使用以下代码完成:
srand(static_cast<unsigned int>(time(0)));
random_shuffle(scores.begin(), scores.end());
我接受代码运行时没有错误,其他机器看到的是随机洗牌,但是当我运行这段代码时,值显然没有洗牌。这是一个较大程序的一部分,当其他人运行该程序时,这些值显然会被打乱,但是当我尝试一遍又一遍运行该程序时,这些值不会打乱。我在想,也许是天真地想,这是因为我在MacBook上运行它,还是因为我没有正确地组织文件和文件夹。有人有什么想法吗?
编辑:这里是完整的代码:#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
vector<int>::const_iterator iter;
cout << "Creating a list of scores.";
vector<int> scores;
scores.push_back(1500);
scores.push_back(3500);
scores.push_back(7500);
cout << "nHigh Scores:n";
for (iter = scores.begin(); iter != scores.end(); ++iter)
{
cout << *iter << endl;
}
cout << "nRandomizing scores.";
srand(static_cast<unsigned int>(time(0)));
random_shuffle(scores.begin(), scores.end());
cout << "nHigh Scores:n";
for (iter = scores.begin(); iter != scores.end(); ++iter)
{
cout << *iter << endl;
}
cout << "nSorting scores.";
sort(scores.begin(), scores.end());
cout << "nHigh Scores:n";
for (iter = scores.begin(); iter != scores.end(); ++iter)
{
cout << *iter << endl;
}
return 0;
}
我想这将正常运行,虽然每个人,这就是为什么我很困惑。
如果你的程序正在做一些不愉快的事情(例如未定义的行为),可能会影响它如何访问任何东西,包括与系统时间相关的数据。
可能与标准库的实现质量有关,因此每次调用它时返回一个常量,而不是一个不同的值。有些实现只访问一次系统时钟,因此多次调用time()
将每次调用返回相同的数据。time()
不需要粒度优于(小于)一秒,所以有相当多的实现选择了一种效率而不是准确性的方法。
快速连续多次调用time()
-包括多次运行您的程序-可能意味着测量相同的时间。
如果没有一个小而完整的代码示例来展示您的问题,以及对运行它的环境的描述,就不可能给出明确的建议。
你的问题更可能出在你的代码或你如何使用你的程序上,而不是你的标准库或硬件的特定问题。但是一个问题的所有相关概率都是非零的
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 查询SQLite数据库中的日期
- 字符串-C++后显示的随机字符
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 如何在ArangoDb AQL查询中指定数据库
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- Qt SQLite没有查询或参数计数不匹配
- 如何使用c++在VS 2019上运行SQL查询
- 将字符随机转换为大写的函数
- 从返回的顶点缓冲区查询顶点结构
- 如何在不同的列中插入随机数量的值? 查询.C++.SQlite 数据库
- MongoDB:查询单个随机文档的最有效方法是什么?
- 查询随机洗牌