C++ | std::iota实现递增序列

C++ | std::iota实现递增序列

传统方式实现递增

// 数组递增
int arr[1000] = {};
for (int i = 0; i < 1000; ++i)
{
	arr[i] = i;
}

// vector递增
std::vector<int> iVec;
iVec.resize(1000);
for (int i = 0; i < 1000; ++i)
{
	iVec[i] = i;
}

Apollo代码里面有一段初始化

lidar_frame_ref_->roi_indices.indices.resize(original_cloud_->size());
// we manually fill roi indices with all cloud point indices
std::iota(lidar_frame_ref_->roi_indices.indices.begin(), lidar_frame_ref_->roi_indices.indices.end(), 0);

代码功能是对lidar_frame_ref_->roi_indices这个vector进行递增初始化,从0开始,一直到original_cloud_->size()大小。

std::itoa源码

/**
*  @brief  Create a range of sequentially increasing values.
*
*  For each element in the range @p [first,last) assigns @p value and
*  increments @p value as if by @p ++value.
*
*  @param  __first  Start of range.
*  @param  __last  End of range.
*  @param  __value  Starting value.
*  @return  Nothing.
*/
template<typename _ForwardIterator, typename _Tp>
void iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value)
{
    for (; __first != __last; ++__first)
    {
        *__first = __value;
        ++__value;
    }
}

源码很清晰。

测试一下

#include <numeric>
#include <iterator>
#include <iostream>
#include <vector>
int main()
{
    // std实现递增
	std::vector<int> iVec(10);
	std::iota(ivec.begin(), ivec.end(), 5);
	for (auto &it: ivec)
	{
		std::cout << it << " ";
	}
  // 或者使用下面语句一次性输出
  std::copy(ivec.begin(), ivec.end(), std::ostream_iterator<int>(std::cout, " "));
  // result:
  5 6 7 8 9 10 11 12 13 14
  
  // 普通数组也可以实现递增
  int arr[10];
  std::iota(arr, arr + 10, 10);		// 10 - 19
  for (int i : arr) std::cout << i << ' ';
  std::cout << '\n';
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值