There is a critical difference between std::fill and memset that is very important to understand. std::fill sets each element to the specified value. memset sets each byte to a specified value.
While they won't produce incorrect results when used appropriately, the mem* family of functions is obsolete. In particular, std::copy, std::move, std::fill, and std::equal provide type-safe, more general, and equally efficient interfaces to perform the same tasks as std::memcpy, std::memmove, std::memset, std::memcmp, and their wide variants.
The std::fill() and std::fill_n() algorithms are used to initialize or reinitialize a sequence with a fixed value.
std::fill函数的作用是:将一个区间的元素都赋予指定的值,即在[first, last)范围内填充指定值。
std::fill_n函数的作用是:在[fist, fist + count)范围内填充指定值。
下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:
#include ""
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <list>
///
// reference: /reference/algorithm/fill/
int test_fill_1()
{
std::vector<int> myvector(8); // myvector: 0 0 0 0 0 0 0 0
std::fill((), () + 4, 5); // myvector: 5 5 5 5 0 0 0 0
std::fill(() + 3, () - 2, 8); // myvector: 5 5 5 8 8 8 0 0
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = (); it != (); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
int test_fill_2()
{
float arr[10];
std::fill(&arr[0], &arr[0] + 10, 1.23);
for (int i = 0; i < 10; i++)
fprintf(stderr, "%f ", arr[i]);
fprintf(stderr, "\n");
return 0;
}
/
// reference: /reference/algorithm/fill_n/
int test_fill_n_1()
{
std::vector<int> myvector(8, 10); // myvector: 10 10 10 10 10 10 10 10
std::fill_n((), 4, 20); // myvector: 20 20 20 20 10 10 10 10
std::fill_n(() + 3, 3, 33); // myvector: 20 20 20 33 33 33 10 10
std::cout << "myvector contains:";
for (std::vector<int>::iterator it = (); it != (); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
GitHub: /fengbingchun/Messy_Test