c++ fill()函数使用
fill函数原型: 参考:http://www.cplusplus.com/reference/algorithm/fill/
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
while (first != last) {
*first = val;
++first;
}
}
赋值范围为:[first,last) 所赋的值为: val
fill函数可以为数组或者vector中的每个元素赋以相同的值,通常用于初始化!
数组的效率往往比vector高,使用assign函数只能对vector赋初值~所以当要对数组赋初值时可以使用fill函数。
fill函数包含在
fill给一维数组赋值:
include <algorithm>
include <stdio.h>
using namespace std;
int v[10];
int main(int argc, char const *argv[])
{
fill(v,v+10,-1);
for (int i = 0; i <10; ++i)
printf("%d ",v[i]);
return 0;
}
输出: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
fill给多维数组赋值:
include <algorithm>
include <stdio.h>
using namespace std;
int v10;
int main(int argc, char const *argv[])
{
fill(v[0],v[0]+10*10,-1);
for (int i = 0; i <10; ++i){
for (int j = 0; j <10 ; ++j){
printf("%d ",v[i][j] );
}
printf("\n");
}
return 0;
}
输出: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1