深入应用C++11 代码优化与工程级应用 ------笔记1

通过函数参数传大量数据:  std::initializer_list

std::initializer_list 不仅可以用来对自定义类型做初始化, 还可以用来传递同类型的数据集合, 代码如下:

void func(std::initializer_list<int> l)
{
    for (auto it = l.begin(); it != l.end();  ++it)
        std::cout << *it << std::endl;
}

int  main(void)
{
    func({});            //一个空集合
    func( { 1, 2, 3 });  //传递{ 1, 2, 3 }
    return 0;
}

for循环遍历 or for_each遍历:

void test1 ()
{
    std::vector<int>  arr;
    //....
    for (auto it = arr.begin(); it != arr.end(); ++it)
    {
        std::cout<< *it << std::endl;
    }
}
void do_count( int n)
{
    std::cout<< n << std::endl;
}
void test2()
{
    std::vector<int> arr;
    //....
    std::for_each(arr.begin(), arr.end(), do_count);
}
void test3()
{
    std::vector<int> arr = {1,2,3};
    //...
    for (auto n: arr) {  // auto可直接换为int. 若改为auto & 则可以对容器元素修改
        std::cout<< n << std::endl;
    }
}

std::set 的内部元素是只读的!  std::map在用C++11里auto& n: arr类似这种循环遍历时, 是不能修改first的(即key).


std::vector<int>arr={1,2,3,4,5};
auto && __range = (arr);
auto  __begin = __range.begin();//__range和arr一样.

迭代器的一种实现:  留意迭代的步长step不一定等于begin-end的约数. step为负数时,operator++实际会减少iterator的值.

template <typename T>
class iterator
{
public:
    using value_type = T;
    using size_type = size_t;
private:
    size_type         cursor_;
    const value_type  step_;
    value_type        value_;
public:
    iterator(size_type  cur_start, value_type begin_val, value_type step_val);
    value_type operator*() const; //取值
    bool operator!=(const iterator& rhs) const;//和另一个迭代器比较
    iterator&  operator++(void); //prefix ++ operator only
};

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值