- truct Point
- {
- int _x;
- int _y;
- };
- int main()
- {
- int array1[] = { 1, 2, 3, 4, 5 };
- int array2[5] = { 0 };
- Point p = { 1, 2 };
- return 0;
- }
- struct Point
- {
- int _x;
- int _y;
- };
- int main()
- {
- int x1 = 1;
- int x2{ 2 };
-
- int array1[]{ 1, 2, 3, 4, 5 };
- int array2[5]{ 0 };
- Point p{ 1, 2 };
-
- // C++11中列表初始化也可以适用于new表达式中
- int* pa = new int[4]{ 0 };
-
- return 0;
- }
- class Date
- {
- public:
- Date(int year, int month, int day)
- :_year(year)
- , _month(month)
- , _day(day)
- {
- cout << "Date(int year, int month, int day)" << endl;
- }
-
- private:
- int _year;
- int _month;
- int _day;
- };
-
- int main()
- {
- Date d1(2022, 1, 1); // old style
-
- // C++11支持的列表初始化,这里会调用构造函数初始化
- Date d2{ 2022, 1, 2 };
- Date d3 = { 2022, 1, 3 };
- return 0;
- }
- int main()
- {
- // the type of il is an initializer_list
- auto il = { 10, 20, 30 };
- cout << typeid(il).name() << endl;
-
- return 0;
- }
- int main()
- {
- vector<int> v = { 1,2,3,4 };
- list<int> lt = { 1,2 };
-
- // 这里{"sort", "排序"}会先初始化构造一个pair对象
- map
dict = { {"sort", "排序"}, {"insert", "插入"} }; -
- // 使用大括号对容器赋值
- v = { 10, 20, 30 };
-
- return 0;
- namespace bit
- {
- template<class T>
- class vector
- {
- public:
- typedef T* iterator;
-
- vector(initializer_list
l) - {
- _start = new T[l.size()];
- _finish = _start + l.size();
- _endofstorage = _start + l.size();
- iterator vit = _start;
- typename initializer_list
::iterator lit = l.begin(); - while (lit != l.end())
- {
- *vit++ = *lit++;
- }
-
-
- //for (auto e : l)
- // *vit++ = e;
- }
-
-
- vector
& operator=(initializer_list l) - {
- vector
tmp(l); - std::swap(_start, tmp._start);
- std::swap(_finish, tmp._finish);
- std::swap(_endofstorage, tmp._endofstorage);
- return *this;
- }
- private:
- iterator _start;
- iterator _finish;
- iterator _endofstorage;
- };
- }
- int main()
- {
- int i = 10;
- auto p = &i;
- auto pf = strcpy;
-
- cout << typeid(p).name() << endl;
- cout << typeid(pf).name() << endl;
-
- map
dict = { {"sort", "排序"}, {"insert", "插入"} }; - //map
::iterator it = dict.begin(); - auto it = dict.begin();
-
- return 0;
- }
- // decltype的一些使用使用场景
- template<class T1, class T2>
- void F(T1 t1, T2 t2)
- {
- decltype(t1 * t2) ret;
- cout << typeid(ret).name() << endl;
- }
-
- int main()
- {
- const int x = 1;
- double y = 2.2;
-
- decltype(x * y) ret; // ret的类型是double
- decltype(&x) p; // p的类型是int*
- cout << typeid(ret).name() << endl;
- cout << typeid(p).name() << endl;
-
- F(1, 'a');
- return 0;
- }
- #ifndef NULL
- #ifdef __cplusplus
- #define NULL 0
- #else
- #define NULL ((void *)0)
- #endif
- #endif

容器中的一些新方法 :
- int main()
- {
- // 以下的p、b、c、*p都是左值
- int* p = new int(0);
- int b = 1;
- const int c = 2;
-
- // 以下几个是对上面左值的左值引用
- int*& rp = p;
- int& rb = b;
- const int& rc = c;
- int& pvalue = *p;
-
- return 0;
- }
- int main()
- {
- double x = 1.1, y = 2.2;
-
- // 以下几个都是常见的右值
- 10;
- x + y;
- fmin(x, y);
-
- // 以下几个都是对右值的右值引用
- int&& rr1 = 10;
- double&& rr2 = x + y;
- double&& rr3 = fmin(x, y);
-
- // 这里编译会报错:error C2106: “=”: 左操作数必须为左值
- 10 = 1;
- x + y = 1;
- fmin(x, y) = 1;
-
- return 0;
- }
- int main()
- {
- // 左值引用只能引用左值,不能引用右值。
- int a = 10;
- int& ra1 = a; // ra为a的别名
- //int& ra2 = 10; // 编译失败,因为10是右值
-
- // const左值引用既可引用左值,也可引用右值
- const int& ra3 = 10;
- const int& ra4 = a;
-
- return 0;
- }
右值引用总结:
- int main()
- {
- // 右值引用只能右值,不能引用左值。
- int&& r1 = 10;
-
- // error C2440: “初始化”: 无法从“int”转换为“int &&”
- // message : 无法将左值绑定到右值引用
- int a = 10;
- int&& r2 = a;
-
- // 右值引用可以引用move以后的左值
- int&& r3 = std::move(a);
-
- return 0;
- }
- namespace bit
- {
- class string
- {
- public:
- typedef char* iterator;
- iterator begin()
- {
- return _str;
- }
- iterator end()
- {
- return _str + _size;
- }
-
- string(const char* str = "")
- :_size(strlen(str))
- , _capacity(_size)
- {
- //cout << "string(char* str)" << endl;
- _str = new char[_capacity + 1];
- strcpy(_str, str);
- }
-
- // s1.swap(s2)
- void swap(string& s)
- {
- ::swap(_str, s._str);
- ::swap(_size, s._size);
- ::swap(_capacity, s._capacity);
- }
-
- // 拷贝构造
- string(const string& s)
- :_str(nullptr)
- {
- cout << "string(const string& s) -- 深拷贝" << endl;
- string tmp(s._str);
- swap(tmp);
- }
-
- // 赋值重载
- string& operator=(const string& s)
- {
- cout << "string& operator=(string s) -- 深拷贝" << endl;
- string tmp(s);
- swap(tmp);
- return *this;
- }
-
- // 移动构造
- string(string&& s)
- :_str(nullptr)
- , _size(0)
- , _capacity(0)
- {
- cout << "string(string&& s) -- 移动语义" << endl;
- swap(s);
- }
-
- // 移动赋值
- string& operator=(string&& s)
- {
- cout << "string& operator=(string&& s) -- 移动语义" << endl;
- swap(s);
- return *this;
- }
-
- ~string()
- {
- delete[] _str;
- _str = nullptr;
- }
-
- char& operator[](size_t pos)
- {
- assert(pos < _size);
- return _str[pos];
- }
-
- void reserve(size_t n)
- {
- if (n > _capacity)
- {
- char* tmp = new char[n + 1];
- strcpy(tmp, _str);
- delete[] _str;
- _str = tmp;
- _capacity = n;
- }
- }
-
- void push_back(char ch)
- {
- if (_size >= _capacity)
- {
- size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
- reserve(newcapacity);
- }
- _str[_size] = ch;
- ++_size;
- _str[_size] = '\0';
- }
-
- //string operator+=(char ch)
- string& operator+=(char ch)
- {
- push_back(ch);
- return *this;
- }
-
- const char* c_str() const
- {
- return _str;
- }
- private:
- char* _str;
- size_t _size;
- size_t _capacity; // 不包含最后做标识的\0
- };
- }
- void func1(bit::string s)
- {}
-
- void func2(const bit::string& s)
- {}
-
- int main()
- {
- bit::string s1("hello world");
- // func1和func2的调用我们可以看到左值引用做参数减少了拷贝,提高效率的使用场景和价值
- func1(s1);
- func2(s1);
-
- // string operator+=(char ch) 传值返回存在深拷贝
- // string& operator+=(char ch) 传左值引用没有拷贝提高了效率
- s1 += '!';
-
- return 0;
- }


- namespace bit
- {
- bit::string to_string(int value)
- {
- bool flag = true;
- if (value < 0)
- {
- flag = false;
- value = 0 - value;
- }
-
- bit::string str;
- while (value > 0)
- {
- int x = value % 10;
- value /= 10;
- str += ('0' + x);
- }
-
- if (flag == false)
- {
- str += '-';
- }
- std::reverse(str.begin(), str.end());
- return str;
- }
- }
-
- int main()
- {
- // 在bit::string to_string(int value)函数中可以看到,这里
- // 只能使用传值返回,传值返回会导致至少1次拷贝构造(如果是一些旧一点的编译器可能是两次拷贝构造)。
- bit::string ret1 = bit::to_string(1234);
- bit::string ret2 = bit::to_string(-1234);
-
- return 0;
- }

- // 移动构造
- string(string&& s)
- :_str(nullptr)
- , _size(0)
- , _capacity(0)
- {
- cout << "string(string&& s) -- 移动语义" << endl;
- swap(s);
- }
-
- int main()
- {
- bit::string ret2 = bit::to_string(-1234);
- return 0;
- }

不仅仅有移动构造,还有移动赋值:
- // 移动赋值
- string& operator=(string&& s)
- {
- cout << "string& operator=(string&& s) -- 移动语义" << endl;
- swap(s);
- return *this;
- }
-
- int main()
- {
- bit::string ret1;
- ret1 = bit::to_string(1234);
- return 0;
- }
-
- // 运行结果:
- // string(string&& s) -- 移动语义
- // string& operator=(string&& s) -- 移动语义
- template<class _Ty>
- inline typename remove_reference<_Ty>::type&& move(_Ty&& _Arg) _NOEXCEPT
- {
- // forward _Arg as movable
- return ((typename remove_reference<_Ty>::type&&)_Arg);
- }
-
- int main()
- {
- bit::string s1("hello world");
- // 这里s1是左值,调用的是拷贝构造
- bit::string s2(s1);
- // 这里我们把s1 move处理以后, 会被当成右值,调用移动构造
- // 但是这里要注意,一般是不要这样用的,因为我们会发现s1的
- // 资源被转移给了s3,s1被置空了。
- bit::string s3(std::move(s1));
-
- return 0;
- }
- void push_back(value_type&& val);
-
- int main()
- {
- list
lt; - bit::string s1("1111");
- // 这里调用的是拷贝构造
- lt.push_back(s1);
-
- // 下面调用都是移动构造
- lt.push_back("2222");
- lt.push_back(std::move(s1));
-
- return 0;
- }
-
- 运行结果:
- // string(const string& s) -- 深拷贝
- // string(string&& s) -- 移动语义
- // string(string&& s) -- 移动语义

- void Fun(int& x) { cout << "左值引用" << endl; }
- void Fun(const int& x) { cout << "const 左值引用" << endl; }
- void Fun(int&& x) { cout << "右值引用" << endl; }
- void Fun(const int&& x) { cout << "const 右值引用" << endl; }
-
-
- // 模板中的&&不代表右值引用,而是万能引用,其既能接收左值又能接收右值。
- // 模板的万能引用只是提供了能够接收同时接收左值引用和右值引用的能力,
- // 但是引用类型的唯一作用就是限制了接收的类型,后续使用中都退化成了左值,
- // 我们希望能够在传递过程中保持它的左值或者右值的属性, 就需要用我们下面学习的完美转发
-
- template<typename T>
- void PerfectForward(T&& t)
- {
- Fun(t);
- }
-
- int main()
- {
- PerfectForward(10); // 右值
-
- int a;
- PerfectForward(a); // 左值
- PerfectForward(std::move(a)); // 右值
-
- const int b = 8;
- PerfectForward(b); // const 左值
- PerfectForward(std::move(b)); // const 右值
-
- return 0;
- }
- void Fun(int& x) { cout << "左值引用" << endl; }
- void Fun(const int& x) { cout << "const 左值引用" << endl; }
-
- void Fun(int&& x) { cout << "右值引用" << endl; }
- void Fun(const int&& x) { cout << "const 右值引用" << endl; }
-
- // std::forward
(t)在传参的过程中保持了t的原生类型属性。 - template<typename T>
- void PerfectForward(T&& t)
- {
- Fun(std::forward
(t)); - }
-
- int main()
- {
- PerfectForward(10); // 右值
-
- int a;
- PerfectForward(a); // 左值
- PerfectForward(std::move(a)); // 右值
-
- const int b = 8;
- PerfectForward(b); // const 左值
- PerfectForward(std::move(b)); // const 右值
-
- return 0;
- }
- template<class T>
- class List
- {
- typedef ListNode
Node; - public:
- List()
- {
- _head = new Node;
- _head->_next = _head;
- _head->_prev = _head;
- }
-
- void PushBack(T&& x)
- {
- //Insert(_head, x);
- Insert(_head, std::forward
(x)); - }
-
- void PushFront(T&& x)
- {
- //Insert(_head->_next, x);
- Insert(_head->_next, std::forward
(x)); - }
-
- void Insert(Node* pos, T&& x)
- {
- Node* prev = pos->_prev;
- Node* newnode = new Node;
- newnode->_data = std::forward
(x); // 关键位置 - // prev newnode pos
- prev->_next = newnode;
- newnode->_prev = prev;
- newnode->_next = pos;
- pos->_prev = newnode;
- }
-
- void Insert(Node* pos, const T& x)
- {
- Node* prev = pos->_prev;
- Node* newnode = new Node;
- newnode->_data = x; // 关键位置
- // prev newnode pos
- prev->_next = newnode;
- newnode->_prev = prev;
- newnode->_next = pos;
- pos->_prev = newnode;
- }
- private:
- Node* _head;
- };
-
- int main()
- {
- List
lt; - lt.PushBack("1111");
- lt.PushFront("2222");
-
- return 0;
- }
- // 以下代码在vs2013中不能体现,在vs2019下才能演示体现上面的特性。
- class Person
- {
- public:
- Person(const char* name = "", int age = 0)
- :_name(name)
- , _age(age)
- {}
-
-
- /*Person(const Person& p)
-
- :_name(p._name)
- ,_age(p._age)
- {}*/
-
-
- /*Person& operator=(const Person& p)
- {
- if(this != &p)
- {
- _name = p._name;
- _age = p._age;
- }
- return *this;
- }*/
-
-
- /*~Person()
- {}*/
-
-
- private:
- bit::string _name;
- int _age;
- };
-
- int main()
- {
- Person s1;
- Person s2 = s1;
- Person s3 = std::move(s1);
- Person s4;
- s4 = std::move(s2);
-
- return 0;
- }
- class Person
- {
- public:
- Person(const char* name = "", int age = 0)
- :_name(name)
- , _age(age)
- {}
-
- Person(const Person& p)
- :_name(p._name)
- , _age(p._age)
- {}
-
- Person(Person&& p) = default;
-
- private:
- bit::string _name;
- int _age;
- };
-
- int main()
- {
- Person s1;
- Person s2 = s1;
- Person s3 = std::move(s1);
- return 0;
- }
- class Person
- {
- public:
- Person(const char* name = "", int age = 0)
- :_name(name)
- , _age(age)
- {}
-
- Person(const Person& p) = delete;
-
- private:
- bit::string _name;
- int _age;
- };
-
- int main()
- {
- Person s1;
- Person s2 = s1;
- Person s3 = std::move(s1);
-
- return 0;
- }
- // Args是一个模板参数包,args是一个函数形参参数包
- // 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。
- template <class ...Args>
- void ShowList(Args... args)
- {}
- // 递归终止函数
- template <class T>
- void ShowList(const T& t)
- {
- cout << t << endl;
- }
-
- // 展开函数
- template <class T, class ...Args>
- void ShowList(T value, Args... args)
- {
- cout << value << " ";
- ShowList(args...);
- }
-
- int main()
- {
- ShowList(1);
- ShowList(1, 'A');
- ShowList(1, 'A', std::string("sort"));
-
- return 0;
- }
- template <class T>
- void PrintArg(T t)
- {
- cout << t << " ";
- }
-
- //展开函数
- template <class ...Args>
- void ShowList(Args... args)
- {
- int arr[] = { (PrintArg(args), 0)... };
- cout << endl;
- }
-
- int main()
- {
- ShowList(1);
- ShowList(1, 'A');
- ShowList(1, 'A', std::string("sort"));
- return 0;
- }
- int main()
- {
- std::list< std::pair<int, char> > mylist;
- // emplace_back支持可变参数,拿到构建pair对象的参数后自己去创建对象
- // 那么在这里我们可以看到除了用法上,和push_back没什么太大的区别
- mylist.emplace_back(10, 'a');
- mylist.emplace_back(20, 'b');
- mylist.emplace_back(make_pair(30, 'c'));
- mylist.push_back(make_pair(40, 'd'));
- mylist.push_back({ 50, 'e' });
-
- for (auto e : mylist)
- cout << e.first << ":" << e.second << endl;
-
- return 0;
- }
-
- int main()
- {
- // 下面我们试一下带有拷贝构造和移动构造的bit::string,再试试呢
- // 我们会发现其实差别也不到,emplace_back是直接构造了,push_back
- // 是先构造,再移动构造,其实也还好。
- std::list< std::pair<int, bit::string> > mylist;
- mylist.emplace_back(10, "sort");
- mylist.emplace_back(make_pair(20, "sort"));
- mylist.push_back(make_pair(30, "sort"));
- mylist.push_back({ 40, "sort" });
-
- return 0;
- }
- #include
- #include
-
- int main()
- {
- int array[] = { 4,1,8,5,3,7,0,9,2,6 };
-
- // 默认按照小于比较,排出来结果是升序
- std::sort(array, array + sizeof(array) / sizeof(array[0]));
-
- // 如果需要降序,需要改变元素的比较规则
- std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
-
- return 0;
- }
- struct Goods
- {
- string _name; // 名字
- double _price; // 价格
- int _evaluate; // 评价
- Goods(const char* str, double price, int evaluate)
- :_name(str)
- , _price(price)
- , _evaluate(evaluate)
- {}
- };
-
-
- struct ComparePriceLess
- {
- bool operator()(const Goods& gl, const Goods& gr)
- {
- return gl._price < gr._price;
- }
- };
-
-
- struct ComparePriceGreater
- {
- bool operator()(const Goods& gl, const Goods& gr)
- {
- return gl._price > gr._price;
- }
- };
-
- int main()
- {
- vector
v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2,3 }, { "菠萝", 1.5, 4 } }; -
- sort(v.begin(), v.end(), ComparePriceLess());
- sort(v.begin(), v.end(), ComparePriceGreater());
- }
- int main()
- {
- vector
v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 }, { "橙子", 2.2, - 3 }, { "菠萝", 1.5, 4 } };
- sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
- return g1._price < g2._price; });
- sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
- return g1._price > g2._price; });
- sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
- return g1._evaluate < g2._evaluate; });
- sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) {
- return g1._evaluate > g2._evaluate; });
- }
注意:在lambda函数定义中,参数列表和返回值类型都是可选部分,而捕捉列表和函数体可以为空。因此C++11中最简单的lambda函数为:[]{}; 该lambda函数不能做任何事情。
- int main()
- {
- // 最简单的lambda表达式, 该lambda表达式没有任何意义
- [] {};
-
- // 省略参数列表和返回值类型,返回值类型由编译器推导为int
- int a = 3, b = 4;
- [=] {return a + 3; };
-
- // 省略了返回值类型,无返回值类型
- auto fun1 = [&](int c) {b = a + c; };
- fun1(10)
- cout << a << " " << b << endl;
-
- // 各部分都很完善的lambda函数
- auto fun2 = [=, &b](int c)->int {return b += a + c; };
- cout << fun2(10) << endl;
-
- // 复制捕捉x
- int x = 10;
- auto add_x = [x](int a) mutable { x *= 2; return a + x; };
- cout << add_x(10) << endl;
- return 0;
- }
注意:
- void (*PF)();
- int main()
- {
- auto f1 = [] {cout << "hello world" << endl; };
- auto f2 = [] {cout << "hello world" << endl; };
-
- //f1 = f2; // 编译失败--->提示找不到operator=()
- // 允许使用一个lambda表达式拷贝构造一个新的副本
- auto f3(f2);
- f3();
-
- // 可以将lambda表达式赋值给相同类型的函数指针
- PF = f2;
- PF();
- return 0;
- }
- class Rate
- {
- public:
- Rate(double rate) : _rate(rate)
- {}
-
- double operator()(double money, int year)
- {
- return money * _rate * year;
- }
-
- private:
- double _rate;
- };
-
- int main()
- {
- // 函数对象
- double rate = 0.49;
- Rate r1(rate);
- r1(10000, 2);
-
- // lamber
- auto r2 = [=](double monty, int year)->double {return monty * rate * year;
- };
- r2(10000, 2);
- return 0;
- }

- ret = func(x);
- // 上面func可能是什么呢?那么func可能是函数名?函数指针?函数对象(仿函数对象)?也有可能
- //是lamber表达式对象?所以这些都是可调用的类型!如此丰富的类型,可能会导致模板的效率低下!
- //为什么呢?我们继续往下看
- template<class F, class T>
- T useF(F f, T x)
- {
- static int count = 0;
- cout << "count:" << ++count << endl;
- cout << "count:" << &count << endl;
- return f(x);
- }
-
- double f(double i)
- {
- return i / 2;
- }
-
- struct Functor
- {
- double operator()(double d)
- {
- return d / 3;
- }
- };
- int main()
- {
- // 函数名
- cout << useF(f, 11.11) << endl;
-
- // 函数对象
- cout << useF(Functor(), 11.11) << endl;
-
- // lamber表达式
- cout << useF([](double d)->double { return d / 4; }, 11.11) << endl;
-
- return 0;
- }
- std::function在头文件
-
- // 类模板原型如下
- template <class T> function; // undefined
-
- template <class Ret, class... Args>
- class function<Ret(Args...)>;
-
- 模板参数说明:
- Ret : 被调用函数的返回类型
- Args…:被调用函数的形参
- // 使用方法如下:
- #include
-
- int f(int a, int b)
- {
- return a + b;
- }
-
- struct Functor
- {
- public:
- int operator() (int a, int b)
- {
- return a + b;
- }
- };
-
- class Plus
- {
- public:
- static int plusi(int a, int b)
- {
- return a + b;
- }
- double plusd(double a, double b)
- {
- return a + b;
- }
- };
-
- int main()
- {
- // 函数名(函数指针)
- std::function<int(int, int)> func1 = f;
- cout << func1(1, 2) << endl;
-
- // 函数对象
- std::function<int(int, int)> func2 = Functor();
- cout << func2(1, 2) << endl;
-
- // lamber表达式
- std::function<int(int, int)> func3 = [](const int a, const int b)
- {return a + b; };
- cout << func3(1, 2) << endl;
-
- // 类的成员函数
- std::function<int(int, int)> func4 = &Plus::plusi;
- cout << func4(1, 2) << endl;
-
- std::function<double(Plus, double, double)> func5 = &Plus::plusd;
- cout << func5(Plus(), 1.1, 2.2) << endl;
-
- return 0;
- }
-
- #include
-
- template<class F, class T>
- T useF(F f, T x)
- {
- static int count = 0;
- cout << "count:" << ++count << endl;
- cout << "count:" << &count << endl;
- return f(x);
- }
-
- double f(double i)
- {
- return i / 2;
- }
-
- struct Functor
- {
- double operator()(double d)
- {
- return d / 3;
- }
- };
-
- int main()
- {
- // 函数名
- std::function<double(double)> func1 = f;
- cout << useF(func1, 11.11) << endl;
-
- // 函数对象
- std::function<double(double)> func2 = Functor();
- cout << useF(func2, 11.11) << endl;
-
- // lamber表达式
- std::function<double(double)> func3 = [](double d)->double { return d /4; };
- cout << useF(func3, 11.11) << endl;
-
- return 0;
- }
- class Solution {
- public:
- int evalRPN(vector
& tokens) { - stack<int> st;
- for (auto& str : tokens)
- {
- if (str == "+" || str == "-" || str == "*" || str == "/")
- {
- int right = st.top();
- st.pop();
- int left = st.top();
- st.pop();
- switch (str[0])
- {
- case '+':
- st.push(left + right);
- break;
- case '-':
- st.push(left - right);
- break;
- case '*':
- st.push(left * right);
- break;
- case '/':
- st.push(left / right);
- break;
- }
- }
- else
- {
- // 1、atoi itoa
- // 2、sprintf scanf
- // 3、stoi to_string C++11
- st.push(stoi(str));
- }
- }
- return st.top();
- }
- };
-
- // 使用包装器以后的玩法
- class Solution {
- public:
- int evalRPN(vector
& tokens) { - stack<int> st;
- map
int(int, int)>> opFuncMap = - {
- { "+", [](int i, int j) {return i + j; } },
- { "-", [](int i, int j) {return i - j; } },
- { "*", [](int i, int j) {return i * j; } },
- { "/", [](int i, int j) {return i / j; } }
- };
-
- for (auto& str : tokens)
- {
- if (opFuncMap.find(str) != opFuncMap.end())
- {
- int right = st.top();
- st.pop();
- int left = st.top();
- st.pop();
-
- st.push(opFuncMap[str](left, right));
- }
- else
- {
- // 1、atoi itoa
- // 2、sprintf scanf
- // 3、stoi to_string C++11
- st.push(stoi(str));
- }
- }
-
- return st.top();
- }
- };
- // 原型如下:
- template <class Fn, class... Args>
- /* unspecified */ bind (Fn&& fn, Args&&... args);
-
- // with return type (2)
- template <class Ret, class Fn, class... Args>
- /* unspecified */ bind (Fn&& fn, Args&&... args);
- // 使用举例
- #include
- int Plus(int a, int b)
- {
- return a + b;
- }
- class Sub
- {
- public:
- int sub(int a, int b)
- {
- return a - b;
- }
- };
-
- int main()
- {
- //表示绑定函数plus 参数分别由调用 func1 的第一,二个参数指定
- std::function<int(int, int)> func1 = std::bind(Plus, placeholders::_1,
- placeholders::_2);
- //auto func1 = std::bind(Plus, placeholders::_1, placeholders::_2);
-
- //func2的类型为 function
与func1类型一样 - //表示绑定函数 plus 的第一,二为: 1, 2
- auto func2 = std::bind(Plus, 1, 2);
- cout << func1(1, 2) << endl;
- cout << func2() << endl;
-
- Sub s;
- // 绑定成员函数
- std::function<int(int, int)> func3 = std::bind(&Sub::sub, s,
- placeholders::_1, placeholders::_2);
-
- // 参数调换顺序
- std::function<int(int, int)> func4 = std::bind(&Sub::sub, s,
- placeholders::_2, placeholders::_1);
- cout << func3(1, 2) << endl;
- cout << func4(1, 2) << endl;
-
- return 0;
- }
|
函数名
|
功能
|
|
thread()
|
构造一个线程对象,没有关联任何线程函数,即没有启动任何线程
|
|
thread(fn, args1, args2, ...)
|
构造一个线程对象,并关联线程函数
fn
,
args1
,
args2
,
...
为线程函数的参数
|
|
get_id()
|
获取线程
id
|
|
jionable()
|
线程是否还在执行,
joinable
代表的是一个正在执行中的线程。
|
|
jion()
|
该函数调用后会阻塞住线程,当该线程结束后,主线程继续执行
|
|
detach()
|
在创建线程对象后马上调用,用于把被创建线程与线程对象分离开,分离
的线程变为后台线程,创建的线程的
"
死活
"
就与主线程无关
|
- #include
- int main()
- {
- std::thread t1;
- cout << t1.get_id() << endl;
- return 0;
- }
- // vs下查看
- typedef struct
- { /* thread identifier for Win32 */
- void *_Hnd; /* Win32 HANDLE */
- unsigned int _Id;
- } _Thrd_imp_t;
- #include
- using namespace std;
- #include
-
- void ThreadFunc(int a)
- {
- cout << "Thread1" << a << endl;
- }
-
- class TF
- {
- public:
- void operator()()
- {
- cout << "Thread3" << endl;
- }
- };
-
- int main()
- {
- // 线程函数为函数指针
- thread t1(ThreadFunc, 10);
-
- // 线程函数为lambda表达式
- thread t2([] {cout << "Thread2" << endl; });
-
- // 线程函数为函数对象
- TF tf;
- thread t3(tf);
-
- t1.join();
- t2.join();
- t3.join();
- cout << "Main thread!" << endl;
- return 0;
- }
- #include
- void ThreadFunc1(int& x)
- {
- x += 10;
- }
-
- void ThreadFunc2(int* x)
- {
- *x += 10;
- }
-
- int main()
- {
- int a = 10;
-
- // 在线程函数中对a修改,不会影响外部实参,因为:线程函数参数虽然是引用方式,但其实际
- 引用的是线程栈中的拷贝
- thread t1(ThreadFunc1, a);
- t1.join();
- cout << a << endl;
-
- // 如果想要通过形参改变外部实参时,必须借助std::ref()函数
- thread t2(ThreadFunc1, std::ref(a);
- t2.join();
- cout << a << endl;
- // 地址的拷贝
- thread t3(ThreadFunc2, &a);
- t3.join();
- cout << a << endl;
- return 0;
- }
- #include
- using namespace std;
- #include
-
- unsigned long sum = 0L;
- void fun(size_t num)
- {
- for (size_t i = 0; i < num; ++i)
- sum++;
- }
-
- int main()
- {
- cout << "Before joining,sum = " << sum << std::endl;
-
- thread t1(fun, 10000000);
- thread t2(fun, 10000000);
- t1.join();
- t2.join();
-
- cout << "After joining,sum = " << sum << std::endl;
- return 0;
- }
- #include
- using namespace std;
- #include
- #include
-
- std::mutex m;
- unsigned long sum = 0L;
-
- void fun(size_t num)
- {
- for (size_t i = 0; i < num; ++i)
- {
- m.lock();
- sum++;
- m.unlock();
- }
- }
-
- int main()
- {
- cout << "Before joining,sum = " << sum << std::endl;
- thread t1(fun, 10000000);
- thread t2(fun, 10000000);
- t1.join();
- t2.join();
-
- cout << "After joining,sum = " << sum << std::endl;
- return 0;
- }
注意:需要使用以上原子操作变量时,必须添加头文件。
- #include
- using namespace std;
- #include
- #include
-
- atomic_long sum{ 0 };
-
- void fun(size_t num)
- {
- for (size_t i = 0; i < num; ++i)
- sum++; // 原子操作
- }
-
- int main()
- {
- cout << "Before joining, sum = " << sum << std::endl;
-
- thread t1(fun, 1000000);
- thread t2(fun, 1000000);
- t1.join();
- t2.join();
-
- cout << "After joining, sum = " << sum << std::endl;
- return 0;
- }
atmoic t; // 声明一个类型为T的原子类型变量t
- #include
- int main()
- {
- atomic<int> a1(0);
- //atomic
a2(a1); // 编译失败 - atomic<int> a2(0);
- //a2 = a1; // 编译失败
- return 0;
- }
- #include
- #include
-
- int number = 0;
- mutex g_lock;
-
- int ThreadProc1()
- {
- for (int i = 0; i < 100; i++)
- {
- g_lock.lock();
- ++number;
- cout << "thread 1 :" << number << endl;
- g_lock.unlock();
- }
- return 0;
- }
-
- int ThreadProc2()
- {
- for (int i = 0; i < 100; i++)
- {
- g_lock.lock();
- --number;
- cout << "thread 2 :" << number << endl;
- g_lock.unlock();
- }
- return 0;
- }
-
- int main()
- {
- thread t1(ThreadProc1);
- thread t2(ThreadProc2);
-
- t1.join();
- t2.join();
- cout << "number:" << number << endl;
- system("pause");
- return 0;
- }
|
函数名
|
函数功能
|
|
lock()
|
上锁:锁住互斥量
|
|
unlock()
|
解锁:释放对互斥量的所有权
|
|
try_lock()
|
尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻
塞
|
线程函数调用try_lock()时,可能会发生以下三种情况:
2. std::recursive_mutex
4. std::recursive_timed_mutex
- template<class _Mutex>
- class lock_guard
- {
- public:
- // 在构造lock_gard时,_Mtx还没有被上锁
- explicit lock_guard(_Mutex& _Mtx)
- : _MyMutex(_Mtx)
- {
- _MyMutex.lock();
- }
-
- // 在构造lock_gard时,_Mtx已经被上锁,此处不需要再上锁
- lock_guard(_Mutex& _Mtx, adopt_lock_t)
- : _MyMutex(_Mtx)
- {}
-
- ~lock_guard() _NOEXCEPT
- {
- _MyMutex.unlock();
- }
-
- lock_guard(const lock_guard&) = delete;
- lock_guard& operator=(const lock_guard&) = delete;
-
- private:
- _Mutex& _MyMutex;
- };
- #include
- #include
- #include
-
- void two_thread_print()
- {
- std::mutex mtx;
- condition_variable c;
- int n = 100;
- bool flag = true;
-
- thread t1([&]() {
- int i = 0;
- while (i < n)
- {
- unique_lock
lock(mtx); - c.wait(lock, [&]()->bool {return flag; });
- cout << i << endl;
- flag = false;
- i += 2; // 偶数
- c.notify_one();
- }
- });
-
- thread t2([&]() {
- int j = 1;
- while (j < n)
- {
- unique_lock
lock(mtx); - c.wait(lock, [&]()->bool {return !flag; });
- cout << j << endl;
- j += 2; // 奇数
- flag = true;
- c.notify_one();
- }
- });
-
- t1.join();
- t2.join();
- }
-
- int main()
- {
- two_thread_print();
- return 0;
- }