C++中std::fill/std::fill_n的使用

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 "fill.hpp"
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <list>

///
// reference: http://www.cplusplus.com/reference/algorithm/fill/
int test_fill_1()
{
	std::vector<int> myvector(8); // myvector: 0 0 0 0 0 0 0 0

	std::fill(myvector.begin(), myvector.begin() + 4, 5); // myvector: 5 5 5 5 0 0 0 0
	std::fill(myvector.begin() + 3, myvector.end() - 2, 8); // myvector: 5 5 5 8 8 8 0 0

	std::cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++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: http://www.cplusplus.com/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(myvector.begin(), 4, 20); // myvector: 20 20 20 20 10 10 10 10
	std::fill_n(myvector.begin() + 3, 3, 33); // myvector: 20 20 20 33 33 33 10 10

	std::cout << "myvector contains:";
	for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
		std::cout << ' ' << *it;
	std::cout << '\n';

	return 0;
}

GitHubhttp://github.com/fengbingchun/Messy_Test

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值