zoukankan      html  css  js  c++  java
  • 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:

    1
    2
    3
    4
    5
    6
    7
    8
    
    template <class ForwardIterator, class T>
      void fill (ForwardIterator first, ForwardIterator last, const T& val)
    {
      while (first != last) {
        *first = val;
        ++first;
      }
    }

    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一样了?

  • 相关阅读:
    资源链接
    python pip下载速度慢的解决方法
    淘宝 NPM 镜像
    python学习链接
    Linux升级python3之后yum不能正常使用解决方法一:重新配置yum源
    rand和srand的用法
    static与volatile的用法
    CentOS 7
    C++类(Class)总结
    简单的linux命令
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758887.html
Copyright © 2011-2022 走看看