C++新特性复习1 版本11

参照来自于:

cppreference.com

老实说,我是毕业不久就开始用C++,原因就是VC++,当时用来做界面。还好吧,不是觉得太难,起码对数学底子没有要求,后面偶尔也用用,但是整体还是C居多。现在项目又要用,但是很多语法有点看不懂了,所以复习一下下。

先从11开始吧,

从特性上看:指针方面unique_ptr,shared_ptr,weak_ptr。条件语句  for − range-for。初始化initializer_list。容器的新特性:vector − deque − array  list − forward_list unordered_map unordered_multimap unordered_set unordered_multiset。

新的工具库:Metaprogramming library。工具库Function objects − hash,Swap − Type operations,pair − tuple。数学库:Floating-point environment。正则表达式库Regular expressions library。最后是并发库Concurrency support library。

一个个简单看看吧。

一 特性

1 auto类型

这个很嗲啊。。。明天一定要试试!

auto x = 10;  // x is int
auto y = 1.5; // y is double

2 range-for

就是简化了的for,还行吧。虽然python这些特性早就烂大街了。

std::vector<int> v = {1, 2, 3, 4};
for (int i : v) {
  std::cout << i << ' ';
}

3 lambda

这个确实不爱用。。。

4 智能指针

大概看了下,就是只用管分配内存就行了,释放内存可以自动搞。

分配的时候使用auto uniquePtr = std::make_unique<int[]>(5);类似这样的写法。空了还是多练练吧。。。

std::unique_ptr<int> p1(new int(10));
std::shared_ptr<int> p2 = std::make_shared<int>(20);

5 编译时期断言

还行吧,这个有的话也行。。。

std::unique_ptr<int> p1(new int(10));
std::shared_ptr<int> p2 = std::make_shared<int>(20);

6 新的null,nullptr。这个其实简单,照着用就行了。

int* p = nullptr;

7 强枚举。

解决枚举冲突,还行吧。

enum class Color { Red, Green, Blue };
Color c = Color::Red;

8 常量表达式,constexpr

好像有用,有好像没用。。

constexpr int square(int x) { return x * x; }
int y = square(5); // y 在编译期被计算为 25

9 长长整形long long int

64位整形数

long long int largeNumber = 10000000000LL;

10 initializer_list

用花括号初始化。好像也是python玩烂了的。。。

std::vector<int> vec = {1, 2, 3, 4, 5};  // 使用 initializer_list 初始化 vector

二 库

1 标准线程库 (Thread library)

void threadFunction() {
  std::cout << "Hello from thread!\n";
}

std::thread t(threadFunction);
t.join();

2 随机数库

还行吧,一般用C的也不是不行。。。

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
std::cout << dis(gen); // 随机输出 1 到 6 之间的整数

3 正则表达式库

std::regex re("\\d+");
std::smatch match;
if (std::regex_search("123", match, re)) {
  std::cout << "Match found: " << match.str() << '\n';
}

4 新容器

std::array<int, 3> arr = {1, 2, 3};
std::unordered_map<std::string, int> map = {{"one", 1}, {"two", 2}};

5 时间库

auto start = std::chrono::high_resolution_clock::now();
// 执行某些操作
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = end - start;
std::cout << "Operation took " << duration.count() << " seconds.\n";

6 其他

比如一些算法

std::vector<int> vec = {1, 2, 3, 4, 5};
bool allPositive = std::all_of(vec.begin(), vec.end(), [](int i){ return i > 0; });

感觉就是auto类型和智能指针可以多用用。其它的知道就行了,要用的时候再学也来得及。

但是有一点,如果用了C++11这些特性,和C的差别越来越大了。要移植或者混用,到时候麻烦的事情会更多。到底用不用呢?真的要tradeoff。。。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值