您好,欢迎来到飒榕旅游知识分享网。
搜索
您的当前位置:首页STL填充与生成(fill,fill_n,generate,generate_n)的用法

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

来源:飒榕旅游知识分享网
//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;
}

运行结果:

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sarr.cn 版权所有 赣ICP备2024042794号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务