n
个对象对,并将它们存储到vector<pair<Foo, Foo>>
中。该算法涉及随机数生成器。我使用STL <random>
及其组件,如m19937
,uniform_real_distribution
和uniform_int_distribution
。下面是我试图做的简化版本,代表我手边的情况。第二个循环总是缩短。但是,我没有看到原因。从本质上讲,我从来没有看到程序完全执行。最后两条消息从未显示过。
程序
#include <iostream>
#include <vector>
#include <random>
#include <utility>
// utility
using std::pair;
// random
using std::mt19937;
using std::uniform_int_distribution;
using std::uniform_real_distribution;
// iostream
using std::cout;
using std::endl;
// vector
using std::vector;
class Event{
private:
double x, y;
public:
Event(const double X, const double Y);
};
Event::Event(const double X, const double Y): x(X), y(Y){}
int main(){
cout << "Initializing storage..." << endl;
vector<Event> population;
vector<pair<Event,Event>> selection;
cout << "Initializing necessary member variables..." << endl;
const unsigned int SEED = 14112017;
const unsigned int MAX_ITERATIONS = 10000;
const double MIN = 1;
const double MAX = 10000;
mt19937 engine(SEED);
cout << "Generating the initial population..." << endl;
uniform_real_distribution<> real_distribution(MIN, MAX);
for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
double x = real_distribution(engine);
double y = real_distribution(engine);
Event event(x, y);
population.push_back(event);
}
cout << "Success! The initial population has been generated successfully" << endl;
population.shrink_to_fit();
cout << "Starting the selection process..." << endl;
unsigned int random = 0;
uniform_int_distribution<> int_distribution(MIN, MAX);
for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
random = int_distribution(engine);
Event event_x = population.at(random);
random = int_distribution(engine);
Event event_y = population.at(random);
pair<Event, Event> bound(event_x, event_y);
selection.push_back(bound);
}
cout << "Success! The selection process has been completed successfully" << endl;
selection.shrink_to_fit();
cout << "population size: " << population.size() << endl;
cout << "selection size: " << selection.size() << endl;
return 0;
}
我使用cygwins C ++编译器编译上面的代码,然后在命令提示符下执行代码。操作系统是Windows 10 x64。该盒子有32 GB的内存。
答案 0 :(得分:1)
uniform_int_distribution
的构造函数如下:
explicit uniform_int_distribution( IntType a = 0,
IntType b = std::numeric_limits<IntType>::max() );
默认情况下,它返回一个整数,该整数涵盖该类型的所有正值。范围包括第二个参数的值。如果不这样做,那么指定我们想要所有正整数将是麻烦的。
cppreference.com没有记录,但C ++标准确实: Thanks @Cubbi
这记录在on cppreference.com或C ++标准中:
26.5.8.2.1班级模板uniform_int_distribution [rand.dist.uni.int]
1 uniform_int_distribution随机数 分布产生随机整数i,a≤i≤b,分布 根据常数离散概率函数
[...]
// constructors and reset functions explicit uniform_int_distribution(IntType a = 0, IntType b = numeric_limits<IntType>::max());
下面:
uniform_int_distribution<> int_distribution(MIN, MAX);
for(unsigned int i = 0; i < MAX_ITERATIONS; ++i){
random = int_distribution(engine);
Event event_x = population.at(random);
random = int_distribution(engine);
Event event_y = population.at(random);
random
可以取值MAX
,这超出population
向量的范围。