C++ fill 和memset
以下内容来自www.cplusplus.com---------------------------------------------------
FILL:
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val);
Fill range with value
Assigns val to all the elements in the range [first,last)
.
The behavior of this function template is equivalent to:
|
|
MEMSET:
void * memset ( void * ptr, int value, size_t num );
Fill block of memorySets the first num bytes
of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).------------------------------------------------------------------------------------------------------可以看出:fill是按元素填充而memset是按字节填充.
代码如下:
#include<iostream> #include<cstring> using namespace std; int main(void) { int test[100]; fill(test,test+100,1); cout<<"case 1:"<<endl; for(int i=0;i<100;i++) cout<<test[i]<<" "; cout<<endl; memset(test,1,sizeof(test)); cout<<"case 2:"<<endl; for(int i=0;i<100;i++) cout<<test[i]<<" "; cout<<endl; memset(test,1,100*sizeof(int)); cout<<"case 3:"<<endl; for(int i=0;i<100;i++) cout<<test[i]<<" "; cout<<endl; }
运行结果如下:
fill按元素填充,所以数组里有100个1;
memset按字节填充,int有四个字节,1*2^24+1*2^16+1*2^8+1*2^0=16843009,数组里有100个16843009
哦?所以说清零的话fill和memset一样了?