2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

0〜n-1の整数をシャッフルする(STLバージョン)

Last updated at Posted at 2016-04-15

学生時代に書いた(2004年ごろと思われる)コードが発掘されたのでさらしてみる。
とりあえず引数を与えず実行しちゃあかんです。

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

class Random
{
public:
    Random(int seed = std::time(NULL)) {
        std::srand(static_cast<unsigned>(seed));
    };  
    virtual ~Random() {}; 

    std::ptrdiff_t operator()(std::ptrdiff_t arg) const {
        return static_cast<std::ptrdiff_t>(arg * static_cast<double>(std::rand()) / RAND_MAX);
    };  
};

template <typename T> class Generator_base
{
public:
    Generator_base(const T init = T(0)) : val(init) {}; 
    virtual ~Generator_base() {}; 
    virtual T operator()() = 0;

protected:
    T val;
};

template <typename T> class IncrementGenerator : public Generator_base<T>
{
public:
    IncrementGenerator(const T init = T(0)) : Generator_base<T>(init) {}; 
    virtual ~IncrementGenerator() {}; 
    virtual T operator()() {
        return Generator_base<T>::val++;
    }   
};

int main(int argc, char * argv[])
{
    std::vector<int> data(atoi(argv[1]));
    IncrementGenerator<int> gen(0);
    Random r;
    std::ostream_iterator<int> os_itrt(std::cout, " ");

    std::generate(data.begin(), data.end(), gen);
    std::random_shuffle(data.begin(), data.end(), r); 
    std::copy(data.begin(), data.end(), os_itrt);

    return 0;
}
/* Local Variables: */
/* compile-command: "g++ -O2 -Wall random.cc" */
/* End: */

[追記1 2015.04.15]
C++14でstd::rand()std::random_shuffle()は非推奨になってます。
代わりに乱数ライブラリ<random>std::shuffle()を使いましょう。

2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?