【C++】fill函數,fill與memset函數的區別

轉載自:http://blog.csdn.net/liuchuo/article/details/52296646


【C++】fill函數,fill與memset函數的區別

  • memset函數

    • 按照字節填充某字符
    • 在頭文件<cstring>裏面
  • fill函數

    • 按照單元賦值,將一個區間的元素都賦同一個值
    • 在頭文件<algorithm>裏面
  • 因爲memset函數按照字節填充,所以一般memset只能用來填充char型數組,(因爲只有char型佔一個字節)如果填充int型數組,除了0和-1,其他的不能。因爲只有00000000 = 0,-1同理,如果我們把每一位都填充“1”,會導致變成填充入“11111111”

  • 而fill函數可以賦值任何,而且使用方法特別簡便:

    • fill(arr, arr + n, 要填入的內容);
    • 例如:
#include <cstdio>
#include <algorithm>
using namespace std;
int main() {
    int arr[10];
    fill(arr, arr + 10, 2);
    return 0;
}

  • vector也可以:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main(){
    vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    fill(v.begin(), v.end(), -1);
    return 0;
}    

  • 而memset的使用方法是:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int a[20];
    memset(a, 0, sizeof a);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章