后面的几篇博客会讲STL的算法,这玩意看起来挺玄乎,其实就是一堆函数而已,没啥。
本文主要讲:
fill:把容器中一定范围内的元素设定为某一个值,参数是:开始,结束,数值
fill_n:把容器中一定范围内的元素设定为某一个值,参数是:开始,count,数值,就是从某个位置开始,设定n个值,n就是这个count。
generate:使用一个生成函数为容器中一定范围内的元素创建新的值。
generate_n:使用一个生成函数为容器中一定范围内的元素创建新的值。也是创建N个值。
// Fig22_26_STL_Algorithms_fill_generate.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//Standard library algorithms fill,fill_n,generate,generate_n.
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
char nextletter();//prototype of generator function
int main()
{
// std::cout << "Hello World!\n";
vector <char> chars(10);
ostream_iterator <char> output(cout," ");
std::fill(chars.begin(),chars.end(),'5');//fill chars with 5s
cout << "Vector chars after filling with 5s:\n";
std::copy(chars.begin(),chars.end(),output);
//fill first five elements with A
std::fill_n(chars.begin(),5,'A');
cout << "\n\nVector chars after filling five elements with As:\n";
std::copy(chars.begin(), chars.end(), output);
//**************************************//
//generate values for all elements of chars with nextletter
std::generate(chars.begin(),chars.end(),nextletter);
cout << "\n\nVector chars after generating letters A----J:\n";
std::copy(chars.begin(), chars.end(), output);//A,B,C,D,E,F,G,H,I,J,
//generate values for first five elements of chars with nextletter
std::generate_n(chars.begin(),5,nextletter);
cout << "\n\nVector chars after generating K----O for the first five elements:\n";
std::copy(chars.begin(), chars.end(), output);
cout << endl;
}//end main()
char nextletter()
{
static char letter = 'A';
return letter++;
}//end function nextletter
运行结果:
Vector chars after filling with 5s:
5 5 5 5 5 5 5 5 5 5
Vector chars after filling five elements with As:
A A A A A 5 5 5 5 5
Vector chars after generating letters A----J:
A B C D E F G H I J
Vector chars after generating K----O for the first five elements:
K L M N O F G H I J