C++ fill 、 fill_n & memset函數
在寫程序時,往往需要對某一容器內的元素進行清零或賦值處理,我們來看看c++ 中fill(),fill_n()和memset()這三個函數是如何做的吧:
1、fill()與fill_n()函數
因爲是面向容器的操作,這兩個函數包含在<algorithm>頭文件中。
fill()函數原型爲
template<class ForwardIterator, class T>
void fill(ForwardIterator first, ForwardIterator last, const T& value);</span>
因此可以通過其對數組元素進行統一賦值操作,而省去了for循環的麻煩,注意賦值區間爲一個半開半閉區間[first,last),所以last不包括在內
完整程序示例如下:
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int a[5];
<span style="white-space:pre"> </span>fill(a,a+5,2);
for(int i=0; i<5;++i)
<span style="white-space:pre"> </span>printf("%d ",a[i]);
>return 0;
}
輸出結果爲
2 2 2 2 2<span style="font-family: Arial, Helvetica, sans-serif;"> </span><img src="" alt="" style="font-family: Arial, Helvetica, sans-serif;" />
當然也可以用fill_n達到同樣的效果
fill_n的函數原型爲
template<class OutputIterator, class Size, class Type> void fill_n(OutputIterator _First,Size _Count, const Type& _Val);其中_First爲起始地址,_Count爲從_Fisrst開始要賦值的元素個數,_val爲要賦的值
完整代碼示例如下:
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
<span style="white-space:pre"> </span>int a[5];
<span style="white-space:pre"> </span>fill_n(a,5,2);
for(int i=0; i<5;++i)
printf("%d ",a[i]);
return 0;
}
輸出結果爲2 2 2 2 2
2、memset()函數
void *memset(void *s, int ch, size_t n);
其中s爲所指向的內存,ch爲要賦的值,而n爲元素個數#include<cstdio>
#include<memory>
using namespace std;
int main()
{
int a[5];
memset(a,2,sizeof(a));
for(int i=0; i<5;++i)
printf("%d ",a[i]);
return 0;
}
運行結果爲:33686018 33686018 33686018 33686018 33686018