-
-
[分享]《探索现代化C++》泛读笔记摘要12
-
发表于: 2022-9-21 19:39 4688
-
《探索现代化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++11for (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; |
赞赏
他的文章
- 定位Windows分页结构内存区域 7582
- [原创]2022年,工业级EDR绕过蓝图 29583
- [分享]《探索现代化C++》泛读笔记摘要20 完! 7597
- [分享]《探索现代化C++》泛读笔记摘要19 7856
- [原创]摘微过滤驱动回调的研究-续 10706
赞赏
雪币:
留言: