1. 程式人生 > >STL演算法 -------- 填充新值

STL演算法 -------- 填充新值

1. fill(b, e, v)

2. fill_n(b, n, v)

3.generate(b, e, p )

4.generate_n(b, n, p)

#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <string>
#include <list>
#include <iterator>
#include <time.h>

using namespace std;

int main( int argc, char** argv )
{
	list<string> lst;
	lst.push_back("hello");
	lst.push_back("hi");
	lst.push_back("how are you");
	fill(lst.begin(), lst.end(), "hao");

	/*
	for(vector<int>::iterator itr=vec.begin(); itr!=vec.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;*/
	for(list<string>::iterator itr=lst.begin(); itr!=lst.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;

	list<string> lst2;
	fill_n(back_inserter(lst2), 9, "hello");
	for(list<string>::iterator itr=lst2.begin(); itr!=lst2.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
	fill_n(ostream_iterator<float>(cout, " "), 10, 7.7);
	
	fill(lst2.begin(), lst2.end(), "again");
	for(list<string>::iterator itr=lst2.begin(); itr!=lst2.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;

	fill_n(lst2.begin(), lst2.size()-2, "hi");
	for(list<string>::iterator itr=lst2.begin(); itr!=lst2.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;

	list<string>::iterator pos1, pos2;
	pos1 = lst2.begin();
	pos2 = lst2.end();
	fill(++pos1, --pos2, "hmmm");
	for(list<string>::iterator itr=lst2.begin(); itr!=lst2.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;

	srand(time(NULL));
	list<int> ilst;
	generate_n(back_inserter(ilst), 5, rand);
	for(list<int>::iterator itr=ilst.begin(); itr!=ilst.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
	generate(ilst.begin(), ilst.end(), rand);
	for(list<int>::iterator itr=ilst.begin(); itr!=ilst.end(); ++itr)
	{
		cout<<*itr<<' ';
	}cout<<endl;
	

	return 0;
}