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

  • 相关阅读:
    Hibernate Annotation 生成数据库表(UUId)
    Hibernate用注解生成表
    Java语言 链接Oracle数据库
    Oracle 启动监听命令
    java.lang.IllegalArgumentException异常 数据库别名问题
    java.lang.IllegalArgumentException异常 返回值类型的问题
    java.lang.IllegalArgumentException异常 配置文件的问题
    JUnit 异常处理
    DIV水平垂直布局
    Java 链接SQL Server 数据库
  • 原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758887.html
Copyright © 2011-2022 走看看