不能std::shuffle?
Not able to std::shuffle?
Code 是基本的:
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>
int main(int argc, const char *argv[]) {
std::vector<int> mSet = { 1, 2, 3, 4 };
auto timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::seed_seq ss{ uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed >> 32) };
std::mt19937_64 rng;
std::shuffle(mSet.begin(), mSet.end(), rng);
for (size_t i = 0; i < mSet.size(); i++) {
std::cout << mSet[i] << " ";
}
}
它总是向我显示相同的序列。我哪里错了?
当你实例化rng
时,你没有使用ss
。因此,您的种子不会被使用,序列将始终相同。
看起来你的意思是:
std::mt19937_64 rng{ss};
您的编译器应该警告您 ss
未被使用。您是否出于某种原因关闭了警告? 不幸的是,即使 -Wextra
.
GCC 似乎也没有对此发出警告
Code 是基本的:
#include <iostream>
#include <vector>
#include <random>
#include <chrono>
#include <algorithm>
int main(int argc, const char *argv[]) {
std::vector<int> mSet = { 1, 2, 3, 4 };
auto timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
std::seed_seq ss{ uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed >> 32) };
std::mt19937_64 rng;
std::shuffle(mSet.begin(), mSet.end(), rng);
for (size_t i = 0; i < mSet.size(); i++) {
std::cout << mSet[i] << " ";
}
}
它总是向我显示相同的序列。我哪里错了?
当你实例化rng
时,你没有使用ss
。因此,您的种子不会被使用,序列将始终相同。
看起来你的意思是:
std::mt19937_64 rng{ss};
您的编译器应该警告您 不幸的是,即使 ss
未被使用。您是否出于某种原因关闭了警告?-Wextra
.