查询随机洗牌

Inquiry about random shuffle

本文关键字:随机 查询      更新时间:2023-10-16

昨天我问了一个关于这个的问题,但是由于沟通不周,这个话题被搁置了。所以我试着运行一个程序来洗牌向量中的元素。该部分使用以下代码完成:

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() -包括多次运行您的程序-可能意味着测量相同的时间。

如果没有一个小而完整的代码示例来展示您的问题,以及对运行它的环境的描述,就不可能给出明确的建议。

你的问题更可能出在你的代码或你如何使用你的程序上,而不是你的标准库或硬件的特定问题。但是一个问题的所有相关概率都是非零的