首页
社区
课程
招聘
[分享]《探索现代化C++》泛读笔记摘要12
2022-9-21 19:39 3900

[分享]《探索现代化C++》泛读笔记摘要12

2022-9-21 19:39
3900

《探索现代化C++》泛读笔记摘要12

Chapter 3 通用编程

C++11 参数不定的模板参数 Variadic Templates

1
2
3
4
5
6
7
8
9
10
11
template<typename T>
inline T sum(T t) { return t; }
 
template <typename T,typename ...P>
inline T sum(T t,P ...p)
{
    return t+sum(p...);
}
 
auto s= sum(-7, 3.7f, 9u, -2.6);
std::cout << "s is " << s << " and its type is " << typeid(s).name() << ".\n";

计算参数个数

1
2
3
4
5
6
template<typename ...P>
void count(P ...p)
{
    cout<<"You have "<<sizeof...(P)<<" parameters.\n";
    ...
}

Chapter 4 C++库

STL 标准模板库

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
#include <list>
#include <numeric>
 
int main()
{
    std::vector<double> vec; // fill the vector...
    std::list<double> lst; // fill the list...
    double vec_sum = std::accumulate(begin(vec), end(vec), 0.0);
    double lst_sum = std::accumulate(begin(lst), end(lst), 0.0);
}

迭代器

1
2
3
4
5
6
7
using namespace std;
std::list<int> l= {3, 5, 9, 7}; // C++11
for (list<int>::iterator it= l.begin(); it != l.end(); ++it)
{
    int i= *it;
    cout << i << endl;
}

现代化C++写法

1
2
3
4
5
std::list<int> l = {3,5,9,7};
for(auto it=begin(l),e=end(l);it!=e;++it){
    int i = *it;
    std::cout<<i<<std::endl;
}

C++17 创建一个常引用 as_const

1
2
3
for (auto it = begin(as_const(l)), e = end(as_const(l)); it != e; ++it) {
        // ...
}

C++14 cbegin,cend

1
2
3
for (auto it = cbegin(l); it != cend(l); ++it) {
 
}

range-based 版,根据需求写。

1
2
3
4
5
6
7
8
9
10
11
12
std::list<int> l = {3,5,9,7};
for(auto i:l)
    std::cout<<i<<std::endl;
 
for(auto i:as_const(l))
    std::cout<<i<<std::endl;
 
for(auto& i:l)
    std::cout<<i<<std::endl;
 
for(const auto& i:l)
    std::cout<<i<<std::endl;

[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课

收藏
点赞1
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回