allocator

allocator #include <memory> allocator<T> a 定义一个名为a的allocator对象,它可以为类型为T的对象分配内存 a.allocate(n) 分配一段原始的、未构造的内存,保存n个类型为T的对象 a.deallocate(p,n) 释放

bind

bind

auto g = bind(f, arg_list)

用我自己的话来说,就是把原来函数f的参数重新安排,可以直接绑定值,也可以使用占位符placeholder,达到减少参数或者调换参数顺序的作用。

插入迭代器

插入迭代器

接受一个容器,生成一个迭代器,实现向给定容器插入元素

操作

it = t

在it指定的当前位置插入值t,且根据插入迭代器的类型不同,分别调用c.push_back(t), c.oush_front(t), c.insert(t,p)

*it, it++, ++it

有这些形式,但是什么都不做

输入输出流迭代器

输入输出流迭代器

istream_iterator

  • 创建一个istream_iterator,然后把它绑定到一个流
  • 如果默认初始化,则是一个尾后值的迭代器

ostream_iterator

1
2
ostream_iterator<T> out(os)  //out将类型为T的值写到os流中
ostream_iterator<T> out(os, d)  //out将类型为T的值写到os流中,且在后面加上字符串d

有了输入输出流迭代器,我们可以把输入输出流当作容器来使用,在拷贝,初始化等等有和容器操作相同的形式,代码比较好看

例子

codewar 题1

大数,阶乘,小数位数

在codewar的一道题

Consider the following numbers (where n! is factorial(n)):

u1 = (1 / 1!) * (1!)
u2 = (1 / 2!) * (1! + 2!)
u3 = (1 / 3!) * (1! + 2! + 3!)
un = (1 / n!) * (1! + 2! + 3! + … + n!)
Which will win: 1 / n! or (1! + 2! + 3! + … + n!)?

Are these numbers going to 0 because of 1/n! or to infinity due to the sum of factorials or to another number?

Task

Calculate (1 / n!) * (1! + 2! + 3! + … + n!) for a given n, where n is an integer greater or equal to 1.

To avoid discussions about rounding, return the result truncated to 6 decimal places, for example:

1.0000989217538616 will be truncated to 1.000098
1.2125000000000001 will be truncated to 1.2125
Remark

Keep in mind that factorials grow rather rapidly, and you need to handle large inputs.