vector上的random_shuffle与main.cpp中的srand(time(NULL))产生相同的结果

时间:2014-01-20 09:41:32

标签: c++ eclipse random vector shuffle

我试图用随机shuffle对一个int的向量进行随机播放,但每次都会返回相同的序列。我在主cpp文件中添加了一个srand(time(NULL)),这没有任何作用。我已经尝试将srand函数添加到shuffleclass类的全局主体,这也无济于事。

代码:

//============================================================================
// Name        : random_shuffle_example.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 <cstdlib>
#include <vector>
#include <ctime>
#include <algorithm>
#include "ShuffleClass.h"

using namespace std;

int main() {
    srand( time ( NULL ) );
    ShuffleClass * shuffleObject = new ShuffleClass;
    shuffleObject -> shuffle();
    shuffleObject -> toScreen();
    return 0;
}

/*
 * ShuffleClass.h
 *
 *  Created on: Jan 20, 2014
 *      Author: edwinrietmeijer
 */

#ifndef SHUFFLECLASS_H_
#define SHUFFLECLASS_H_

#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm>

class ShuffleClass {
private:
    const static int numbersToShuffle[];
    std::vector<int> myvector;
public:
    ShuffleClass();
    void shuffle();
    void toScreen();
    virtual ~ShuffleClass();
};

#endif

/*
 * ShuffleClass.cpp
 *
 *  Created on: Jan 20, 2014
 *      Author: edwinrietmeijer
 */

#include "ShuffleClass.h"

const int ShuffleClass::numbersToShuffle[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

ShuffleClass::ShuffleClass() {
    for ( int i = 0; i < 10; i++ )
        ShuffleClass::myvector.push_back( numbersToShuffle[ i ] );
    // TODO Auto-generated constructor stub
}

void ShuffleClass::shuffle() {
    std::random_shuffle( ShuffleClass::myvector.begin(), ShuffleClass::myvector.end() );
}

void ShuffleClass::toScreen() {
    std::vector<int>::iterator pos;
    for ( pos = myvector.begin(); pos != myvector.end(); ++pos )
        std::cout << *pos << " ";
    std::cout << std::endl;
}


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

0 个答案:

没有答案