C++标准库笔记之一 Chapter 3 New Language Features

来源:互联网 发布:淘宝上有正品蜘蛛刀吗 编辑:程序博客网 时间:2024/06/15 11:35

最近想到学习应当持之以恒,而自己对C++ Standard Library一直以来又很有兴趣进行一次系统的学习,因此便开始阅读《The C++ Standard Library: A Tutorial and Reference (2nd Edition)》. 阅读必当实践,因此也顺手按照书本写下多个示例程序,并把它们罗列在属于同一章节或同一主题的一个cpp文件中。写到后面,发现应该把书中的一些重要语句也加到程序中作为注释以帮助理解。在之后章节的笔记中,注释方面应该会做得更好。

这本书共分上下两册,英文版共1000多页。希望自己能够持之以恒地学习完,完成这个自我挑战!(当然,在坚持阅读这本书的同时,可能我也会阅读一些其他的书籍,因此拖的时间会比较长。)以下便是对Chapter 3 - New Language Features 的总结。

关于本笔记代码的下载,可见于:https://github.com/FinixLei/Learn_CppStandardLibrary

// g++ ./chapter_3.cpp -o ./chapter -std=c++11#include <functional>#include <string>#include <vector>#include <initializer_list>#include <bitset>#include <iostream>using namespace std;void test_uniform_initialization();void print_assist(std::initializer_list<int> vals);void test_initializer_list();void test_for_each();void test_new_string_literals();void test_constexpr();void my_print();void test_variadic_template();void test_lambda_1();void test_lambda_2();void test_lambda_3();void test_lambda_4();void test_member_templates();void test_template_constructor();void test_explicit_initialization_for_fundamental_types();int main() {test_explicit_initialization_for_fundamental_types();// test_template_constructor();// test_member_templates();// test_lambda_4();// test_lambda_3();// test_lambda_2();// test_lambda_1();// test_variadic_template();// test_constexpr();// test_new_string_literals();// test_for_each();// test_initializer_list(); // test_uniform_initialization();return 0;}void test_explicit_initialization_for_fundamental_types() {// If use the syntax of an explicit constructor call without arguments,// fundamental types are initialized with zero. int i1;int i2 = int();int i3{};cout <<"i1 = " <<i1 <<endl;  // undefined valuecout <<"i2 = " <<i2 <<endl;  // intialized with zerocout <<"i3 = " <<i3 <<endl;  // intialized with zero (since C++11)}template <typename T>class MyClass2 {public:// copy constructor with implicit type conversion // does not suppress implicit copy constructortemplate <typename U>MyClass2 (const MyClass2<U>& x){};MyClass2(){}};void test_template_constructor() {MyClass2<double> xd;MyClass2<double> xd2(xd);// calls implicitly generated copy constructorMyClass2<int> xi(xd);// calls template constructor}template <typename T>class MyClass {private:T value;public:template <typename X>// member templates allows different template typesvoid assign(const MyClass<X>& x) {// Otherwise, if change X to T, the following "d.assign(i)" will failvalue = x.getValue();}T getValue() const {return value;}};void test_member_templates() {MyClass<double> d;MyClass<int> i;d.assign(d);// OKd.assign(i);// OK (int is assinable to double)}std::function<int(int,int)> returnLambda() {// You can use std::function<> class template to specify a general type for functional programming. // That class template provides the only way to specify the return type of a function returning a lambda. return [] (int x, int y) {return x * y;};}void test_lambda_4() {auto lf = returnLambda();cout <<lf(6, 7) <<endl;  // 42}void test_lambda_3() {// With mutable, a lambda becomes stateful even if the state is passed by valueint id = 0;auto f = [id] () mutable {cout <<"id = " <<id <<endl;++id;};id = 200;f();  // id = 0f();  // id = 1f();  // id = 2cout <<id <<endl;  // 200}void test_lambda_2() {// [=] means the outer scope is passed to the lambda by value// [&] means the outer scope is passed to the lambda by referenceint x = 0;int y = 10;auto qqq = [x, &y] {cout << "x=" <<x << "\t" <<"y=" <<y <<endl;++y; };x = y = 77;qqq();  // x=77 y=77qqq();  // x=77 y=78cout <<"Finally y=" <<y <<endl;  // Finally y=79}void test_lambda_1() {    // A lambda is a definition of functionality taht can be defined inside statements and expressions.     // Thus you can use lambda as an inline function.         auto l_01 = [] {        std::cout <<"Hello, Lambda" <<std::endl;    };    l_01();        // You can specify parameters, mutable, an exception specification, attribute specifiers, and the return type.     // All of them are optional. Thus, the syntax of a lambda is either     // [...] {...}    // or     // [...] (...) mutable or throwSpec -> retType {...}        auto l_02 = [] (const std::string& s) {        std::cout <<s <<std::endl;    };    l_02("Hi, Lambda, again!");        // To specify a return type, you can use the new syntax C++ also provides for oridinary functions.        auto l_03 = [] ()->double {        return 100;    };    auto dd = l_03();    std::cout <<"size of dd is " <<sizeof(dd) <<std::endl;}void my_print(){}template <typename T, typename... Types>void my_print(const T& firstArg, const Types&... args) {std::cout <<firstArg <<std::endl;my_print(args...);  // call my_print() for remaining arguments}void test_variadic_template(){my_print(6.5, "hello", std::bitset<16>(256), 10);}constexpr long square(int x) {return x * x;}void test_constexpr(){float array[square(9)];cout <<"size = " <<sizeof(array) / sizeof(float);}void test_new_string_literals() {string str = R"(\\n)";cout << "str = " << str <<endl;string str2 = R"delim(\\\\n)delim";cout <<"str2 = " <<str2 <<endl;}void test_for_each() {for (int i : {2, 3, 4, 5, 6}) {cout <<i <<",";}cout <<endl;int array[] {1, 2, 3, 4, 5};long sum = 0;for (int x : array) {sum += x;}for (auto elem : {sum, sum*2, sum*4}) {cout <<elem <<endl;}}void print_assist(std::initializer_list<int> vals) {for (auto p=vals.begin(); p!=vals.end(); ++p) {cout <<*p <<endl;}}void test_initializer_list() {print_assist({12, 11, 10, 9, 8});}void test_uniform_initialization() {int values[]{15,25,35};int array_size = sizeof(values)/sizeof(int);for (int i=0; i<array_size; i++) {cout <<values[i] <<", ";}cout <<endl;std::vector<int> v{ 1, 3, 5, 7, 9 };auto pos = v.begin();  // std::vector<int>::iterator pos = v.begin();while (pos != v.end()) {cout <<*pos <<", ";pos++;}cout <<endl;}

0 0
原创粉丝点击