この問題を扱ってから数時間が経ちました。誰かが私が間違ってやっていることを指摘できるかどうか、もし可能ならばそれをどう修正するか、私は疑問に思いました。本質的には、私は単にn
個のオブジェクトペアを生成し、それらをvector<pair<Foo, Foo>>
に格納しようとしています。このアルゴリズムは乱数発生器を含む。私はSTL <random>
とそのコンポーネントをm19937
,uniform_real_distribution
、uniform_int_distribution
のように使用します。以下は、私が手にしたケースを表現しようとしているものの単純化されたバージョンです。 2番目のループは常に短くなります。しかし、私はなぜその理由を見落とす。基本的には、プログラムが完全に実行されることは決してありません。最後の2つのメッセージは表示されません。プログラムは完全に実行されず、いずれもクラッシュしません
プログラム
#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;
}
Iはcygwins C++コンパイラを使用して、上記コンパイル、およびIは、コマンドプロンプトでコードを実行します。 OSはWindows 10 x64です。ボックスには32 GBのメモリがあります。次のように
プログラムの実行時に[ヒント](http://coliru.stacked-crooked.com/a/822f8e9a73ec402d)を取得しているはずです。 – nwp
'-std = C++ 11 'を使って実行しますが、ヒントやエラーは表示されません。 '-std = C++ 11 -Wall -g' –
これは残念です。しかし、プログラムには未定義の振る舞いはありませんが、未処理の例外がスローされます。そのため、デバッガで実行すると、範囲外のアクセスが発生した行でプログラムを一時停止する必要があります。 – nwp