STL填充与生成(fill,fill_n,generate,generate_n)的用法

来源:互联网 发布:电魂网络千股千评 编辑:程序博客网 时间:2024/04/28 23:54
//Generators.h#ifndef GENERATORS_H#define GENERATORS_H#include <cstring>#include <set>#include <cstdlib>class SkipGen{int i;int skp;public:SkipGen(int start = 0, int skip = 1):i(start), skp(skip){}int operator()(){int r = i;i += skp;return r;}};class URandGen{std::set<int> used;int limit;public:URandGen(int lim) : limit(lim){}int operator()(){while(true){int i = int(std::rand()) % limit;if(used.find(i) == used.end()){used.insert(i);return i;}}}};class CharGen{static const char* source;static const int len;public:char operator()(){return source[std::rand() % len];}};#endif


//PrintSequance.h#ifndef PRINTSEQUENCE_H#define PRINTSEQUENCE_H#include <algorithm>#include <iostream>#include <iterator>template<typename Iter>void print(Iter first, Iter last, const char *nm = "",   const char *sep = "\n",   std::ostream &os = std::cout){if(nm != 0 && *nm != '\n')os << nm << ": " << sep;typedef typename std::iterator_traits<Iter>::value_type T;std::copy(first, last,std::ostream_iterator<T>(std::cout, sep));os << std::endl;}#endif   //PRINTSEQUENCE_H



//Generators.cpp#include "Generators.h"const char* CharGen::source = "ABCDEFGHIJK""LMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";const int CharGen::len = std::strlen(source);


//FillGeneratorTest.cpp#include <vector>#include <algorithm>#include <string>#include "Generators.h"#include "PrintSequence.h"using namespace std;int main(){vector<string> v1(5);fill(v1.begin(), v1.end(), "howdy");print(v1.begin(), v1.end(), "v1", " ");vector<string> v2;fill_n(back_inserter(v2), 7, "bye");print(v2.begin(), v2.end(), "v2");vector<int> v3(10);generate(v3.begin(), v3.end(), SkipGen(4, 5));print(v3.begin(), v3.end(), "v3", " ");vector<int> v4;generate_n(back_inserter(v4), 15, URandGen(30));print(v4.begin(), v4.end(), "v4", " ");system("pause");return 0;}

运行结果:


原创粉丝点击