C++特性

C++11、C++14、C++17增加的新关键字和新语法特性

#include <iostream>
#include <map>
#include <vector>
#include <tuple>
#include <algorithm>

using namespace std;

int main(int argc, char **argv) {
  // 1. 列表初始化
  // 定义数组
  double b = double{1.2};
  int arr1[3]{1, 2, 3};    // -> int arr[3] = {1, 2, 3};
  vector<int> iv{1, 2, 3};
  map<int, string> key_value{{1, "a"}, {2, "b"}};
  string str{"Hello World"};

  // new
  int *a = new int{3};
  int *arr2 = new int[]{1, 2, 3};

  // 2. 自动类型推导:auto(C++11)
  for (vector<int>::const_iterator itr = iv.cbegin(); itr != iv.cend(); itr++)
    cout << *itr << " ";
  cout << endl;

  // 使用auto
  // 由于 cbegin() 返回 vector<int>::const_iterator
  // 所以 itr 的类型也应该是 vector<int>::const_iterator
  for (auto itr = iv.cbegin(); itr != iv.cend(); itr++)
    cout << *itr << " ";
  cout << endl;

  // 3.循环体
  // 未使用新特性
  for (int i = 0; i < iv.size(); i++)
    cout << iv[i] << " ";
  cout << endl;

  // 使用新特性
  for (int i : iv)
    cout << i << " ";
  cout << endl;

  // 这种循环支持大部分数据类型,比如数组,容器,字符串,迭代器等等

  // map循环体
  for (auto p : key_value)
    cout << p.first << " " << p.second << endl;

  // 4.lambda表达式
  /* lambda表达式可以使得编程非常简洁,尤其适用于简单的函数和只使用一次的函数,形式如下
     [capture list] (params list) mutable exception-> return type { function
     body } 各项含义如下: capture list:捕获外部变量列表 params list:形参列表
     mutable指示符:用来说用是否可以修改捕获的变量
     exception:异常设定
     return type:返回类型
     function body:函数体 */

  // 定义数组
  vector<int> vec1{1, 6, 2, 5, 3, 9, 7};
  // 打印排序前数组
  for (int i : vec1)
    cout << i << " ";
  cout << endl;

  // 数组排序(升序),使用algorithm标准库和lambda函数
  sort(vec1.begin(), vec1.end(),
       [](int param1, int param2) -> bool { return param1 < param2; });
  // 打印排序后数组
  for (int i : vec1)
    cout << i << " ";
  cout << endl;

  // 5.tuple:可以传入多个不同类型数据,避免嵌套pair
  // 支持多种不同类型数据
  auto tup1 = std::make_tuple("Hello World!", 'a', 3.14, 0);

  // 方便拆分
  auto tup2 = std::make_tuple(3.14, 1, 'a');
  double dt; int it; char c;
  std::tie(dt, it, c) = tup2;    // 结果是a = 3.14, b = 1, c = 'a'
  
  // 方便链接
  std::tuple<float, string> tup3(3.14, "pi");
  std::tuple<int, char> tup4(10, 'a');
  auto tup5 = tuple_cat(tup3, tup4);
  
  // C++ 参考手册,可查询新特性
  // https://en.cppreference.com/w/cpp
  // http://www.cplusplus.com

  return 0;
}
发布了15 篇原创文章 · 获赞 0 · 访问量 430

猜你喜欢

转载自blog.csdn.net/weixin_46581517/article/details/104913850