随机数生成器有时无法在Eclipse中启动

时间:2014-01-17 18:04:12

标签: eclipse random crash

我编写了一些代码,用于生成一个在查询时返回唯一随机数的对象。然而,每次大约6或7次运行程序都无法启动,似乎没有明显的原因。此外,我的记忆似乎随着时间的推移而下降(使用类中的向量)。有任何想法吗?

 /*
 * Urn.h
 *
 *  Created on: Jan 17, 2014
 *      Author: edwinrietmeijer
 */

#ifndef URN_H_
#define URN_H_

#include <cstdlib>
#include <vector>
#include <iostream>

class Urn {
private:
    int highRand;
    int loRand;
    int numsTotal;
    int numsLeft;
    std::vector<int>numsAvailable;
public:
    Urn();
    int getRand();
    int getSize();
    void reset();
    virtual ~Urn();
};

#endif /* URN_H_ */

/*
 * Urn.cpp
 *
 *  Created on: Jan 17, 2014
 *      Author: edwinrietmeijer
 */

#include "Urn.h"

using namespace std;

Urn::Urn() : highRand( 9 ), loRand( 0 ) {

    vector<int>::iterator pos;
    int newRandom;
    numsTotal = highRand - loRand;
    bool newRandomExists = false;

    while ( numsAvailable.size() < numsTotal + 1 )
    {
        do  {
            newRandomExists = false;
            newRandom = ( rand() % ( numsTotal + 1 ) ) + loRand;
            for ( pos = numsAvailable.begin(); pos != numsAvailable.end(); pos++ ) {
            //  cout << *pos << " ";
                if ( *pos == newRandom ) {
                    newRandomExists = true;
                }
            }
        //  cout << "  Random -> " << newRandom << " " << newRandomExists <<  endl;
        } while ( newRandomExists == true );
        newRandomExists = false;
        numsAvailable.push_back( newRandom );
    }

    cout << endl;
    // List the list
    for (pos = numsAvailable.begin(); pos != numsAvailable.end(); pos++ ) {
//      cout << *pos << " ";
    }
//  cout << endl;
    // TODO Auto-generated constructor stub
}

int Urn::getRand() {
    vector<int>::iterator pos = numsAvailable.begin();
    int numToReturn = numsAvailable.back( );
    numsAvailable.erase( pos  );
    return numToReturn;
}

int Urn::getSize() {
    return numsAvailable.size();
}

void Urn::reset() {

}


Urn::~Urn() {
    // TODO Auto-generated destructor stub
}

//============================================================================
// Name        : UniqueRand.cpp
// Author      : Edwin Rietmeijer
// Version     :
// Copyright   : This code is owned by Edwin Rietmeijer as of 2014
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <string>
#include "Urn.h"

using namespace std;

int main() {
    cout << "Seeding..." << endl;

    srand( time( NULL ) );

    cout << "Getting object..." << endl;

    Urn * urnObject = new Urn;

    cout << urnObject -> getRand();

    return 0;
}

0 个答案:

没有答案