C++新特性学习

C++新特性学习

委托构造函数

c++11

class Test {
public:
	Test(int n) {}
	Test() :Test(0) {}
};

可以避免在不同的构造函数中重复编写相似的初始化代码,提高了代码的可维护性和可读性

初始化列表

struct Data {
	int i = 1;
	float f = 2.0;
	bool b = true;
};

空指针

int main(){
	char *s = NULL;//别用了
	char *s = nullptr;
}

枚举类

enum class Color {
    Red,
    Green,
    Blue
};

int main() {
    Color c = Color::Red;
    if (c == Color::Red) {
    
    }
    return 0;
}

enum 强类型 无法进行隐式转换

类型推导auto

对于各种数据类型,迭代器等可直接用auto进行类型推导

  //迭代器
for (auto it = s.begin(); it != s.end(); it++) {
      cout << *it << ' ';

//数据类型
auto a = 1;

//函数的返回值
auto add(int x,int y){
	return x + y;
}

常量表达式constexpr

将运行时的计算提前到编译时来计算进行优化

可修饰变量,函数等等

constexpr int size = 10;

constexpr int square(int x) {
    return x * x;
}

初始化列表

类似于普通数组的创建

vector<int>a = { 1,2,3,4,5 };
map<int, int>a = { {1,1},{2,3},{3,5} };

基于范围的for循环

一种新的元素遍历

原本的方式

vector<int>v = { 1,2,3 };
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it;
	}

新的遍历方式

vector<int>v = { 1,2,3 };
	for (int c : v) {
	cout << c << endl; //..不需要解引用
	}
	
vector<string>ve = { "早上","好","中国" };
	for (string b : ve) {
	cout << b;
	}
	
map<int, int>map = { {1,1},{2,3},{3,5} };
	for (auto a : map) {
	cout << a.first << "->" << a.second << endl;
	}
	
C++17可以使用	
map<int,string>m = { {1,"早上好"},{2,"你好"},{3,"晚上好"}};
	for (auto [key,val] : m) {
		cout << key << "->" << val << endl;
	}	

智能指针

所需要的头文件 #include<memory>

#include<iostream>
#include<memory>
using namespace std;

struct SomeDate {
	int a, b, c;
};

void f() {
	//常规写法
	//SomeDate* date = new SomeDate;

	//unique_ptr<SomeDate> date(new SomeDate);

	//推荐写法
	auto date = make_unique<SomeDate>();

	date->a = 1;
	date->b = 2;
	date->c = 3;
}

make_unique指向对象唯一的智能指针

需要指针在不同函数间传递,或者多个指针指向同一个对象则使用shared_ptr

Lanbda表达式

int main() {
	vector<int>a = { 1,2,3,4,5 };
	auto it = find_if(a.begin(), a.end(), [](int x) {return x > 3; });
	cout << *it;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值