填充算法

#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
	list<string> slist;
	slist.push_back("xiao cui");
	slist.push_back(" ai");
	slist.push_back(" ni");

	fill(slist.begin(), slist.end(), "ai cui");  //fill() 是填充,用一个迭代器指定一个区间,
	for (list<string>::iterator iter = slist.begin(); iter != slist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	cout << endl << endl;
	
	list<string> slist2;
	fill_n(back_inserter(slist2), 8, "cui");  // fill_n填充时指定填充的个数,
	for (list<string>::iterator iter = slist2.begin(); iter != slist2.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	fill_n(ostream_iterator<float>(cout, " "), 10, 5.5); //ostream_iterator是输出流迭代器, 输出十个5.5
	cout << endl;

	fill(slist2.begin(), slist2.end(), "heng");
	for (list<string>::iterator iter = slist2.begin(); iter != slist2.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	fill_n(slist2.begin(), slist2.size() - 2, "cui");
	for (list<string>::iterator iter = slist2.begin(); iter != slist2.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;

	list<string>::iterator pos1, pos2;
	pos1 = slist2.begin();
	pos2 = slist2.end();

	fill(++pos1, --pos2, "ai"); // fill()只能填充固定的词,
	for (list<string>::iterator iter = slist2.begin(); iter != slist2.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	cout << endl << endl;

	list<int> ilist;
	generate_n(back_inserter(ilist), 6, rand); // rand是随机的添加几个数字,
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;
	generate(ilist.begin(), ilist.end(), rand); // generate也可以使用函数,动态的标量,比较的灵活,
	for (list<int>::iterator iter = ilist.begin(); iter != ilist.end(); ++iter)
		cout << *iter << ' ';
	cout << endl;



	return 0;
}

你可能感兴趣的:(填充算法)