Chinaunix首页 | 论坛 | 博客
  • 博客访问: 276011
  • 博文数量: 65
  • 博客积分: 3091
  • 博客等级: 中校
  • 技术积分: 705
  • 用 户 组: 普通用户
  • 注册时间: 2005-01-25 09:44
文章存档

2013年(2)

2012年(11)

2011年(12)

2010年(13)

2009年(15)

2008年(12)

分类: C/C++

2013-06-05 11:13:22

C++11代码示例:

点击(此处)折叠或打开

  1. /**
  2. -* c++11demo.cpp
  3. -* zsj, 20130415
  4. -* 测试环境:GCC4.8, VS2010
  5. -*/

  6. #include <ctime>
  7. #include <cstring>
  8. #include <cstdlib>
  9. #include <limits>
  10. #include <iostream>
  11. #include <sstream> /* for stringstream */
  12. #include <string>
  13. #include <vector>
  14. #include <map>
  15. #include <list>
  16. #include <algorithm>
  17. #include <functional>
  18. #include <unordered_map>

  19. #include "hash_map"

  20. #include "boost/lexical_cast.hpp"

  21. using namespace std;

  22. typedef enum SexType_E
  23. {
  24.     ESEX_MALE = 0,
  25.     ESEX_FEMAIL = 1,
  26.     ESEX_UNKNOWM = 2,
  27. } SexType;

  28. typedef struct Record_T
  29. {
  30.     char name[16];
  31. } Record;

  32. /*
  33.  * unions
  34.  */
  35. struct point
  36. {
  37.     point() {}
  38.     point(int x, int y): x_(x), y_(y) {}
  39.     int x_, y_;
  40. };
  41. union CPP11_U
  42. {
  43.     int z;
  44.     double w;
  45.     // 合法的 C++11 语句
  46.     point p; // point 有一 non-trivial 建构式,之前的C++标准视作非法
  47.     char *ptr;
  48.     int seq[4];
  49.     vector<int> vi; // not a POD member
  50. };

  51. /*
  52.  * 类型自动推导
  53.  */
  54. template<class T, class U>
  55. void TUmultiply (const vector<T> &vt,
  56.                  const vector<U> &vu)
  57. {
  58.     // ...
  59.     int size = (vt.size() > vu.size()) ? vt.size() : vu.size();

  60.     for(int i = 0; i < size; i++)
  61.         auto tmp = vt[i] * vu[i];
  62.     // ...
  63. }

  64. template< typename LHS, typename RHS>
  65. auto AddingFunc(const LHS &lhs, const RHS &rhs) -> decltype(lhs+rhs)
  66. {
  67.     return lhs + rhs;
  68. }

  69. /*
  70.  * 常量表达式
  71.  */
  72. constexpr int GetFive()
  73. {
  74.     return 5;
  75. }

  76. enum Flags { good=0, fail=1, bad=2, eof=4 };

  77. constexpr int operator| (Flags f1, Flags f2)
  78. {
  79.     return Flags(int(f1) | int(f2));
  80. }

  81. void f(Flags x)
  82. {
  83.     switch (x)
  84.     {
  85.     case bad: /**/
  86.         break;
  87.     case eof: /**/
  88.         break;
  89.     case bad|eof: /**/
  90.         break;
  91.     default: /**/
  92.         break;
  93.     }
  94. }

  95. void ff(Flags f3)
  96. {
  97.     // 错误:因为f3不是常量,所以无法在编译时期计算这个表达式的结果值
  98.     // constexpr int x2 = bad|f3;
  99.     int x3 = bad|f3; // ok,可以在运行时计算
  100. }

  101. struct Point
  102. {
  103.     int x,y;
  104.     constexpr Point(int xx, int yy) : x(xx), y(yy) {}
  105. };

  106. /*
  107.  * decltype grammer
  108.  */
  109. void DcltpF(const vector<int>& va, vector<float>& vb)
  110. {
  111.     // 推断表达式a[0]*b[0]的数据类型,并将其定义为Temp类型
  112.     typedef decltype(va[0]*vb[0]) Tmp;
  113.     // 使用Tmp作为数据类型声明变量,创建对象
  114.     for (int i = 0; i < vb.size(); ++i)
  115.     {
  116.         Tmp *p = new Tmp(va[i]*vb[i]);
  117.         //
  118.     }
  119. }

  120. class X
  121. {
  122.     X& operator=(const X&) = delete; // 禁用类的赋值操作符
  123.     X(const X&) = delete; // 禁用类的复制构造函数
  124. };

  125. class Y
  126. {
  127.     // 使用默认的赋值操作符和复制构造函数
  128.     Y& operator=(const Y&) = default; // 使用默认的赋值操作
  129.     Y(const Y&) = default; // 使用默认的复制构造函数
  130. };

  131. struct Z
  132. {
  133.     Z(long long); // 可以通过long long初始化
  134.     Z(long) = delete; // 但是不能将long long转换为long进行初始化
  135. };

  136. class BigType
  137. {
  138. public:
  139.     BigType Get() { return *this; }

  140. public:
  141.     int attr[1024];
  142.     // ...
  143. };

  144. BigType BigTypeFunc()
  145. {
  146.     return BigType();
  147. }

  148. BigType&& BigTypeFuncRR()
  149. {
  150.     return BigType();
  151. }

  152. BigType& SetBigTypeValueRR(BigType&& bigV)
  153. {
  154.     BigType a = bigV;
  155.     BigType &&rra = a.Get();
  156.     rra.attr[0] = 0;
  157.     return bigV;
  158. }

  159. /*
  160.  * 在缺省情况下,一个类拥有 6 个默认的操作函数:
     * 缺省构造函数 (constructor)           TC( void );
     * 拷贝构造函数 (copy constructor)      TC( const TC &);
     * 缺省析构函数 (destructor)            ~TC( void );
     * 赋值运算符函数 (copy assignment)     TC & operator= (TC &);
     * 取址运算符函数 (address-of)          TC * operator& (void);
     * 常量取址运算符函数 (address-of)      const TC * operator& (void) const;
     * c++11标准新增:
     * 移动构造函数 (move constructor)      TC (TC &&)
     * 移动赋值操作符函数 (move assignment) TC & operator= (TC &&) 
  161.  */
  162. /* 如果显式地指明( 声明、定义、=default 或者 =delete )了移动、复制或者析构函数
  163.  * 的行为,将不会产生默认的移动操作(移动赋值操作符和移动构造函数)。
  164.  * 同时,未声明的复制操作(复制赋值操作符和复制构造函数)会被默认生成,
  165.  * 但是,这是是应该尽量避免的,不要依赖于编译器的这种行为。
  166.  * 如果声明了上述 5 个默认函数中的任何一个,则强烈建议显式地声明所有这 5 个默认函数。
  167.  */
  168. template<class T>
  169. class Handle
  170. {
  171.     T* p;
  172. public:
  173.     Handle(T* pp) : p {pp} // 用户定义构造函数: 没有隐式的复制和移动操作
  174.     {}

  175.     ~Handle()
  176.     {
  177.         delete p;
  178.     }

  179.     Handle(Handle&& h) : p {h.p} // transfer ownership
  180.     { h.p = nullptr; };
  181.     Handle& operator=(Handle&& h) // 传递所有权
  182.     {
  183.         delete p;
  184.         p = h.p;
  185.         h.p = nullptr;
  186.     }

  187.     Handle(const Handle&) = delete; // 禁用复制
  188.     Handle& operator=(const Handle&) = delete;
  189.     // ...
  190. };

  191. /*
  192.  * 委托构造函数(Delegating constructors)
  193.  */
  194. class BadX_Exception
  195. {
  196. public:
  197.     BadX_Exception(int errID)
  198.     {
  199.         // 输出构造函数被调用信息
  200.         std::cout << "BadX_Exception is called" << std::endl;
  201.         error_ID = errID;
  202.     }

  203.     int GetErrorID()
  204.     {
  205.         return error_ID;
  206.     }
  207. private:
  208.     // 错误码
  209.     int error_ID;
  210. };

  211. /*
  212.  * 委托构造函数: Delegating constructors
  213.  */
  214. class DlgtX
  215. {
  216.     int a;
  217. public:
  218.     DlgtX(int x)
  219.     {
  220.         if (0<=x && x<=numeric_limits<int>::max()) a=x;
  221.         else throw BadX_Exception(x);
  222.     }
  223.     // 构造函数X()调用构造函数X(int x)
  224.     DlgtX() :DlgtX {0} { }
  225.     // 构造函数X(string s)调用构造函数X(int x)
  226.     DlgtX(string s) :DlgtX {boost::lexical_cast<int>(s)} { }
  227.     //
  228. };

  229. /*
  230.  * noexcept: 阻止异常的传播与扩散
  231.  */
  232. extern "C" double sqrt(double) noexcept; // 永远不会抛出异常

  233. // 在这里,我不准备处理内存耗尽的异常,所以我只是简单地将函数声明为noexcept
  234. vector<double> my_computation(const vector<double>& v) noexcept
  235. {
  236.     vector<double> res(v.size()); // 可能会抛出异常
  237.     for(int i; i<v.size(); ++i)
  238.         res[i] = sqrt(v[i]);
  239.     return res;
  240. }

  241. /*
  242.  * 外部模板声明
  243.  */
  244. // file A.cpp
  245. // extern template class MyVector<int>; // 消除后续的隐式实例化
  246. // file B.cpp 使MyVector类对客户端(clients)可用(例如,共享库)
  247. // template class MyVector<int>;

  248. /*
  249.  * 序列化 for 循环
  250.  */
  251. void SeqFor(vector<int> &v)
  252. {
  253.     for (auto x : v) cout << x << 'n';
  254.     for (auto &x : v) ++x; // 使用引用,方便我们修改容器中的数据
  255.     for (const auto x :
  256. {
  257.     1,2,3,5,8,13,21,34
  258. })
  259.     cout << x << 'n';
  260. }

  261. /*
  262.  * 初始化列表
  263.  */
  264. // 对变量进行初始化的机制实际上是通过一个可以接受参数类型
  265. // 为std::initializer_list的函数(通常为构造函数)来实现的。
  266. // 例如:
  267. void Init_F(initializer_list<int> args)
  268. {
  269.     for (auto p=args.begin(); p!=args.end(); ++p)
  270.         cout << *p << "n";
  271. }

  272. /*
  273.  * Lambda表达式是一种描述函数对象的机制,
  274.  * 它的主要应用是描述某些具有简单行为的函数
  275.  */
  276. // 一个Lambda表达式可以存取在它被调用的作用域内的局部变量
  277. void Lambda_F(vector<Record>& v)
  278. {
  279.     vector<int> indices(v.size());
  280.     int count = 0;

  281.     generate(indices.begin(), indices.end(),
  282.              [&count]()
  283.     {
  284.         return count++;
  285.     });

  286.     // sort indices in the order determined by the name field of the records:
  287.     std::sort(indices.begin(), indices.end(), [&](int a, int b)
  288.     {
  289.         return v[a].name<v[b].name;
  290.     });
  291.     //
  292. }

  293. /*
  294.  * 返回值类型后置
  295.  */
  296. template<class T, class U>
  297. auto mul(T x, U y) -> decltype(x*y)
  298. {
  299.     return x*y;
  300. }

  301. ///////////////////////////////////////////////////////////////////////////

  302. /*
  303. -* string to time_t
  304. -* 时间格式 2009-3-24 0:00:00 或 2009-3-24
  305. -*/
  306. time_t StringTimedTick(const std::string &strTime)
  307. {
  308.     time_t tickTime;
  309.     char *ptrBegin = (char*) strTime.c_str();
  310.     char *ptr = strstr(ptrBegin, "-");
  311.     if(ptr == nullptr)
  312.     {
  313.         std::cout << "strTime[" << strTime << "%s] err" << std::endl;
  314.         return 0;
  315.     }
  316.     int year = atoi(ptrBegin);
  317.     int month = atoi(ptr + 1);
  318.     ptr = strstr(ptr + 1,"-");
  319.     if(ptr == nullptr)
  320.     {
  321.         std::cout << "strTime[" << strTime << "] err" << std::endl;
  322.         return 0;
  323.     }
  324.     int day = atoi(ptr + 1);
  325.     int hour = 0;
  326.     int minute = 0;
  327.     int second = 0;
  328.     ptr = strstr(ptr + 1, " ");

  329.     //为了兼容有些没精确到时分秒的
  330.     if(ptr != nullptr)
  331.     {
  332.         hour = atoi(ptr + 1);
  333.         ptr = strstr(ptr + 1, ":");
  334.         if(ptr != NULL)
  335.         {
  336.             minute = atoi(ptr + 1);
  337.             ptr = strstr(ptr + 1, ":");
  338.             if(ptr != nullptr)
  339.             {
  340.                 second = atoi(ptr + 1);
  341.             }
  342.         }
  343.     }

  344.     struct tm dateTime;
  345.     memset((void*)&dateTime, 0, sizeof(dateTime));
  346.     dateTime.tm_sec = second;
  347.     dateTime.tm_min = minute;
  348.     dateTime.tm_hour = hour;
  349.     dateTime.tm_mday = day;
  350.     dateTime.tm_mon = month - 1;
  351.     dateTime.tm_year = year - 1900;
  352.     tickTime = mktime(&dateTime);
  353.     return tickTime;
  354. }

  355. /*
  356. -* time_t to string
  357. -*/
  358. std::string & TickTimedString(time_t tickTime, int offSec, std::string &strTime)
  359. {
  360.     struct tm *p;
  361.     std::stringstream out;

  362.     tickTime += offSec;
  363.     p = localtime(&tickTime);

  364.     p->tm_year = p->tm_year + 1900;
  365.     p->tm_mon = p->tm_mon + 1;

  366.     out << p->tm_year << '-' << p->tm_mon << '-' << p->tm_mday
  367.         << ' ' << p->tm_hour << ':' << p->tm_min << ':' << p->tm_sec;
  368.     strTime = out.str();
  369.     //strm << std::setw(4)     //     << std::setw(2) << std::setfill('0')     //     << std::setw(2) << std::setfill('0')     //     << '_' << std::setw(2) << std::setfill('0')     //     << ':' << std::setw(2) << std::setfill('0')     //     << ':' << std::setw(2) << std::setfill('0')     //     << std::hex << std::uppercase << std::setw(4) << std::setfill('0') << dateTime.millitm;
        //strm >> strTime;
  370.     return strTime;
  371. }

  372. /*
  373.  * 测试 map, pair
  374.  */
  375. typedef struct BabyInfo_T
  376. {
  377.     time_t birthTime;
  378.     SexType sex;
  379.     float weight; // gram
  380.     float heighth; // millimeter
  381.     std::string nickName;

  382.     bool operator < (const struct BabyInfo_T &v) const
  383.     {
  384.         return birthTime < v.birthTime;
  385.     }
  386. } BabyInfo;

  387. typedef struct Mother_T
  388. {
  389.     int age;
  390.     std::string name;
  391.     std::string address;
  392. } Mother;

  393. int STL_Map_Test(int argc, char **argv)
  394. {
  395.     std::map<BabyInfo, Mother> bornMap;
  396.     std::pair<BabyInfo, Mother> element;

  397.     BabyInfo babyInfo;
  398.     babyInfo.birthTime = StringTimedTick("2013-3-14 2:34:56");
  399.     babyInfo.sex = ESEX_FEMAIL;

  400.     Mother mother;
  401.     mother.age = 25;
  402.     mother.name = "susan";

  403.     element.first = babyInfo;
  404.     element.second = mother;

  405.     bornMap.insert(element);

  406.     babyInfo.birthTime = StringTimedTick("2013-3-15 13:45:6");
  407.     babyInfo.weight = 3456;
  408.     mother.age = 26;
  409.     mother.name = "jone";
  410.     mother.address = "BeiJing";
  411.     element.first = babyInfo;
  412.     element.second = mother;

  413.     bornMap.insert(element);

  414.     std::string strTime;
  415.     for(std::map<BabyInfo, Mother>::iterator iter = bornMap.begin();
  416.             iter != bornMap.end(); iter++)
  417.     {
  418.         std::cout << TickTimedString(iter->first.birthTime, 0, strTime)
  419.                   << std::endl;
  420.     }

  421.     return 0;
  422. }

  423. /*
  424.  * Hash test
  425.  */

  426. class Usr_Key
  427. {
  428. public:
  429.     Usr_Key(int n, const string &s) : id(n), name(s) { }

  430. public:
  431.     int id;
  432.     std::string name;
  433. };

  434. class Usr_Type
  435. {
  436. public:
  437.     Usr_Type()
  438.     {
  439.         name = model = description = "";
  440.     };
  441.     Usr_Type(const string &s, const string &m, const string &d)
  442.         : name(s), model(m), description(d) { }

  443.     const string &GetName() const
  444.     {
  445.         return name;
  446.     }
  447.     const string &GetModel() const
  448.     {
  449.         return model;
  450.     }
  451.     const string &GetDescription() const
  452.     {
  453.         return description;
  454.     }

  455. private:
  456.     string name, model, description;
  457. };

  458. /*
  459.  * deine an unordered map with Usr_Key instances as keys
  460.  * and Usr_Type instances as values
  461.  */
  462. // The HASH object can either be a class(which implementing a
  463. // function call operator that takes an object of type KEY
  464. // as argument and returns a unique value of type size_t based
  465. // on it), or a pointer to a function.
  466. class Usr_HashKey
  467. {
  468. public:
  469.     size_t operator() (const Usr_Key &x) const
  470.     {
  471.         hash<string> z;
  472.         return z(x.name) * 100 + x.id;
  473.     }
  474. };
  475. // if the class we want to use as key overloads the operator==,
  476. // then we do not need to provide an argument for the EQUAL_TO
  477. // template argument
  478. class Usr_HashPredicate
  479. {
  480. public:
  481.     bool operator() (const Usr_Key &a, const Usr_Key &b) const
  482.     {
  483.         return (a.name == b.name) && (a.id == b.id);
  484.     }
  485. };

  486. ostream &operator<< (ostream &os, const Usr_Key &a)
  487. {
  488.     return os << a.id << "(" << a.name << ") ";
  489. }

  490. ostream &operator<< (ostream &os, const Usr_Type &a)
  491. {
  492.     return os << "Name: " << a.GetName() << "; Model: " << a.GetModel()
  493.            << "; Description: " << a.GetDescription();
  494. }
  495. //template < class Key, // unordered_map::key_type
  496. // class T, // unordered_map::mapped_type
  497. // class Hash = hash<Key>, // unordered_map::hasher
  498. // class Pred = equal_to<Key>, // unordered_map::key_equal
  499. // class Alloc = allocator< pair<const Key, T> > // unordered_map::allocator_type
  500. // > class unordered_map;
  501. int STL_Hash_Test(int argc, char **argv)
  502. {
  503.     std::unordered_map<int, std::string> hashIntStrMap;
  504.     std::unordered_map<Usr_Key, Usr_Type,
  505.         Usr_HashKey, Usr_HashPredicate> hashObjMap;

  506.     hashIntStrMap[5] = "name string 1";
  507.     Usr_Key key(1, "first");
  508.     hashObjMap[key] = Usr_Type("title", "segment", "description");

  509.     //std::unordered_map<Usr_Key, Usr_Type,
  510.     // Usr_HashKey, Usr_HashPredicate> :: const_iterator theIterator;
  511.     for ( auto iter = hashObjMap.begin() ; iter != hashObjMap.end() ; iter++ )
  512.     {
  513.         std::cout << iter->first
  514.                   << " "
  515.                   << iter->second
  516.                   << " : "
  517.                   << iter->second
  518.                   << endl;
  519.     }

  520.     return 0;
  521. }

  522. /*
  523.  * 主函数
  524.  */
  525. int main(int argc, char **argv)
  526. {
  527.     using namespace std;

  528.     cout << "Hello world!" << endl;

  529.     /*
  530.      * const grammer
  531.      */
  532.     const string cnstStr = "const string";
  533.     string varStr("variable string");

  534.     basic_string <char>::const_iterator itC;
  535.     basic_string <char>::iterator itV;

  536.     itV = varStr.begin();
  537.     itC = cnstStr.begin(); // as error: itV = cnstStr.begin();

  538.     /*
  539.      * enum example
  540.      */
  541.     enum Alert { green, yellow, election, red }; // 传统枚举
  542.     //Alert a1 = 7; // 错误,传统枚举不是强类型的,a没有数据类型
  543.     int a2 = red; // 正确,Alert 默认转换成 int
  544.     // 新的具有类域和强类型的枚举类
  545.     enum class Color
  546.     {
  547.         red, blue
  548.     };
  549.     // 枚举类的枚举值在类的外部时不可见的
  550.     //int a3 = blue; // 错误,blue并没有在类域中
  551.     // 不会默认地转换成int
  552.     //Color c = 7; // 错误,没有默认的 int 到 Color 的转换
  553.     int a4 = Alert::red; // 在 C++98中是错误的,但是在C++0x中是正确的
  554.     //int a5 = Color::blue; // 错误,没有Color到int的默认转换
  555.     Color a6 = Color::blue; // 正确

  556.     enum class CColor : char // compact representation
  557.     {
  558.         red, blue
  559.     };
  560.     // 默认情况下,枚举值的底层数据类型为 int
  561.     enum class TrafficLight
  562.     {
  563.         red, yellow, green
  564.     };
  565.     // E的体积是多大呢?
  566.     enum E { E1 = 1, E2 = 2, Ebig = 0xFFFFFFF0U };
  567.     // 不管旧的规则怎么定义,比如依赖于实现等
  568.     // 现在我们可以指定枚举值的底层数据类型
  569.     enum EE : unsigned long { EE1 = 1, EE2 = 2, EEbig = 0xFFFFFFF0U };
  570.     // 指定枚举值的底层数据类型,使得前向声明成为可能
  571.     enum class Color_code : char; // (前向) 声明
  572.     void foobar(Color_code *p); // 前向声明的使用
  573.     // 定义
  574.     enum class Color_code : char
  575.     {
  576.         red, yellow, green, blue
  577.     };

  578.     /*
  579.      * 常量表达式(constexpr)
  580.      */
  581.     constexpr int x1 = bad|eof; // ok

  582.     constexpr Point origo(0,0);
  583.     constexpr int z = origo.x;

  584.     constexpr Point a[] = {Point(0,0), Point(1,1), Point(2,2) };
  585.     constexpr int x = a[1].x; // x 变成 1

  586.     int some_value[GetFive() + 5]; // 欲产生 10 个整数的阵列。合法的C++11语句


  587.     /*
  588.      * 测试 initialization list
  589.      */
  590.     vector<double> v = { 1, 2, 3.456, 99.99 };
  591.     list< pair<string, string> > languages =
  592.     {
  593.         {"Nygaard","Simula"}, {"Richards","BCPL"}, {"Ritchie","C"}
  594.     };
  595.     map< vector<string>, vector<int> > years =
  596.     {
  597.         { {"Maurice","Vincent", "Wilkes"},
  598.             {1913, 1945, 1951, 1967, 2000}
  599.         },
  600.         { {"Martin", "Ritchards"},
  601.             {1982, 2003, 2007}
  602.         },
  603.         { {"David", "John", "Wheeler"},
  604.             {1927, 1947, 1951, 2004}
  605.         }
  606.     };

  607.     Init_F( {1,2});
  608.     Init_F( {23,345,4567,56789});
  609.     Init_F( {}); // 以空列表为参数调用f()
  610.     //Init_F {1,2}; // 错误:缺少函数调用符号( )
  611.     years.insert( {{"Bjarne","Stroustrup"},{1950, 1975, 1985}});

  612.     vector<double> v1(7); // 正确: v1有7个元素
  613.     //v2 = 9; // 错误: 无法将int转换为vector
  614.     //vector<double> v3 = 9; // 错误: 无法将int转换为vector

  615.     void f(const vector<double>&);
  616.     //Init_F(9); // 错误: 无法将int转换为vector

  617.     vector<double> v4 {7}; // 正确: v1有一个元素,其值为7
  618.     v1 = {9}; // 正确,v1现在有一个值为9的元素
  619.     vector<double> v6 = {9}; // 正确: 有一个值为9的元素
  620.     Init_F( {9}); // 正确: f函数将以{ 9 }为参数被调用

  621.     vector< vector<double> > vs =
  622.     {
  623.         // 正确: 显式构造(10个元素,值为double的默认值)
  624.         vector<double>(10),
  625.         vector<double>{10}, // 正确:显式构造(1个元素,值为10)
  626.         //10 //错误 :vector的构造函数是显式的
  627.     };

  628.     /*
  629.      * decltype grammer
  630.      */
  631.     const std::vector<int> vecint(1);
  632.     auto av = vecint[0]; // av 為 int 类型
  633.     decltype(vecint[0]) dcltpb = 0; // b 为 const int& 类型,
  634.     // 即 std::vector<int>::operator[](size_type)const 的回返类型

  635.     /*
  636.      * Lambda statement
  637.      */
  638.     vector <int> numbers(10);
  639.     generate(numbers.begin(), numbers.end(),
  640.              [] {return rand() % 100;});
  641.     int odd_count = 0;
  642.     for_each(numbers.begin(), numbers.end(),
  643.              [&odd_count](int value)
  644.     {
  645.         if (value % 2 != 0) odd_count++;
  646.     });
  647.     int seqStep = 2;
  648.     int seqValue = -seqStep;
  649.     vector<int> seq(10);
  650.     generate(seq.begin(), seq.end(),
  651.              [&seqValue, seqStep] {return seqValue += seqStep;});
  652.     seqValue = -seqStep;
  653.     generate(seq.begin(), seq.end(),
  654.              [seqValue, seqStep]() mutable {return seqValue += seqStep;});
  655.     auto lamdaF = [](int x, int y) -> int
  656.     {
  657.         x *= x;
  658.         return x + y;
  659.     };

  660.     /*
  661.     * 右值引用
  662.     */
  663.     BigType bigVar;
  664.     BigType& r1 = bigVar; // OK: 将r1绑定到变量a(一个左值)
  665.     //BigType& r2 = BigTypeFunc(); // Error: 其返回的是一个右值,无法绑定

  666.     BigType&& rr1 = BigTypeFunc(); // OK: 将rr1绑定到临时变量
  667.     //BigType&& rr2 = bigVar; // Error: 无法将右值引用rr2绑定到左值a

  668.     /*
  669.      * 静态(编译期)断言由一个常量表达式及一个字符串文本构成
  670.      */
  671.     //static_assert(sizeof(long) >= 8,
  672.     // "64-bit code generation required for this library.");


  673.     /*
  674.      * map, pair and hash example
  675.      */
  676.     STL_Map_Test(argc, argv);
  677.     STL_Hash_Test(argc, argv);

  678.     return 0;
  679. }
参考资料:




阅读(767) | 评论(0) | 转发(0) |
0

上一篇:Lex 与 Yacc 介绍

下一篇:多线程测试程序

给主人留下些什么吧!~~