C++11标准模板(STL)- 算法 - 数值运算(std::iota)

定义于头文件 <algorithm>

算法库提供大量用途的函数(例如查找、排序、计数、操作),它们在元素范围上操作。注意范围定义为 [first, last) ,其中 last 指代要查询或修改的最后元素的后一个元素。

用从起始值开始连续递增的值填充一个范围

std::iota

template< class ForwardIterator, class T >
void iota( ForwardIterator first, ForwardIterator last, T value );

(C++11 起)

以始于 value 并重复地求值 ++value 的顺序递增值填充范围 [first, last)

等价操作:

*(d_first)   = value;
*(d_first+1) = ++value;
*(d_first+2) = ++value;
*(d_first+3) = ++value;
...

参数

first, last-以 value 开始,按顺序递增填充的值的范围
value-要存储的初始值,表达式 ++value 必须为良式

返回值

(无)

复杂度

正好 last - first 次自增与赋值。

可能的实现

template<class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value)
{
    while(first != last) {
        *first++ = value;
        ++value;
    }
}

调用示例

#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <iterator>
#include <time.h>

using namespace std;

struct Cell
{
    int x;
    int y;

    Cell &operator +=(const Cell &cell)
    {
        x += cell.x;
        y += cell.y;
        return *this;
    }

    Cell &operator ++()
    {
        x += 1;
        y += 1;
        return *this;
    }

    bool operator <(const Cell &cell) const
    {
        if (x == cell.x)
        {
            return y < cell.y;
        }
        else
        {
            return x < cell.x;
        }
    }

    bool operator ==(const Cell &cell) const
    {
        return x == cell.x && y == cell.y;
    }
};

std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
    os << "{" << cell.x << "," << cell.y << "}";
    return os;
}

int main()
{
    std::mt19937 g{std::random_device{}()};

    srand((unsigned)time(NULL));;

    std::cout << std::boolalpha;

    std::function<Cell()> generate = []()
    {
        int n = std::rand() % 10 + 100;
        Cell cell{n, n};
        return cell;
    };

    // 初始化cells1
    std::list<vector<Cell>> lCells(6, vector<Cell>(6));
    //用从起始值开始连续递增的值填充一个范围
    for (vector<Cell> &vCells : lCells)
    {
        std::iota(vCells.begin(), vCells.end(), generate());
    }

    size_t index = 0;
    for (vector<Cell> &vCells : lCells)
    {
        std::cout << "lCells " << index << " ";
        std::copy(vCells.begin(), vCells.end(), std::ostream_iterator<Cell>(std::cout, " "));
        std::cout << std::endl;
        index++;
    }

    return 0;
}

输出

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值