「std::generate」の版間の差分

提供: C++入門
移動: 案内検索
(関連項目)
(関連項目)
行67: 行67:
 
* [[std::for_each]]
 
* [[std::for_each]]
 
* [[std::fill]]
 
* [[std::fill]]
 +
* [[std::iota]]
 
* [[乱数]]
 
* [[乱数]]
 
<!-- vim: filetype=mediawiki -->
 
<!-- vim: filetype=mediawiki -->

2014年1月3日 (金) 23:58時点における版

std::generate とは、レンジのエレメントに対して、ジェネレータを呼び出し、ジェネレータの値を割り当てる機能を提供します。

読み方

std::generate
えすてぃーでぃー じぇねれーと

概要

std::generateは、コンテナの各要素に対して、ジェネレータの生成した値を代入します。ジェネレータには、関数や関数オブジェクトラムダ式が使用できます。

generate1.cpp の例

ソースコード generate1.cpp

#include <iostream>	// cout
#include <algorithm>	// generate
#include <vector>	// vector
#include <ctime>	// time
#include <cstdlib>	//srand,rand
using namespace std;
int main(int argc, char const* argv[])
{
        std::srand( unsigned ( time(NULL) ) );
 
        vector<int> v(8);
 
        generate(v.begin(), v.end(),
                        []()->int {
                                return (rand() % 100);
                        }
                );
 
        for(auto i: v) {
                cout << i << " ";
        }
        cout << endl;
 
        generate(v.begin(), v.end(),
                        []()->int {
                                static int i = 0;
                                return (++i);
                        }
                );
 
        for(auto i: v) {
                cout << i << " ";
        }
        cout << endl;
 
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  generate1.cpp -o generate1

実行例

% ./generate1
13 52 63 78 63 84 64 47
1 2 3 4 5 6 7 8

関連項目