fill 与memset 给整个数组赋值

1.fill()函数包含在<algorithm>头文件中。原型为 

   template<class ForwardIterator, class T>

    void fill(ForwardIterator first, ForwardIterator last, const T& value);
      其中first与last分别代表迭代器的起始与终止,而value即为要赋的值

因此可以通过其对数组元素进行统一赋值操作,而省去了for循环的麻烦,注意赋值区间为一个半开半闭区间[first,last),所以last不包括在内

2.memset()函数
对于数组的清零操作往往靠它实现,但是它只能对数组赋值-1,0,1,其他的话无法达到目的。

3.事例

#include <bits/stdc++.h>
using namespace std;

int main()
{
   int a[4];
   memset(a,0,sizeof(a));
   for(int i=0;i<=3;i++)
    printf("%d ",a[i]);
    printf("%\n");
   fill(a,a+3,1);
   for(int i=0;i<=3;i++)
    printf("%d ",a[i]);
    return 0;
}
//输出结果
// 0 0 0 0
// 1 1 1 0   说明了fill的半开半闭的性质

#include <bits/stdc++.h>
using namespace std;

int main()
{
   int a[4];
   memset(a,5,sizeof(a));
   for(int i=0;i<=3;i++)
    printf("%d ",a[i]);
    printf("%\n");
}
//输出结果 
// 84215045 84215045 84215045 84215045
//说明 memset只可以赋值0 -1 1 





版权声明:本文为deepseazbw原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。