constexpr 常量表达式,编译器直接推断值。using代替typedef(using可以指定模版类型别名)
#include <iostream>
#include <vector>
using namespace std;
constexpr int new_size(int x) {return 42*x;}
template< class T >
class A {
T _a;
public:
A(T a): _a(a) {
}
void show() const {
cout << _a << endl;
}
};
template< typename T >
using Table = vector< A<T> >; //有模版的别名不能声明在函数内
int main(int argc, char* argv[]) {
constexpr int foo = new_size(10);
cout << foo << endl;
//int i = 10;
const int i = 10;
constexpr int a = new_size(i);
typedef int INT;
INT b = 10;
using inte = int;
inte c = 10;
cout << b << " " << c << endl;
A<int> d(10);
d.show();
//typedef vector< A<T> > Table; // error
/*template< typename T >
using Table = vector< A<T> >; //有模版的别名不能声明在函数内
*/
Table<int> t;
t.push_back(d);
t[0].show();
cout << "Hello world!" << endl;
return 0;
}
使用default声明默认构造函数,vector的emplace_back函数,字符串和数字之间的互换函数(to_string, stod...)
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
class A {
private:
int _a = 10, _b = 10;
public:
constexpr A(int a, int b): _a(a), _b(b) {
}
A() = default; //使用默认构造函数,内联
// A(int a, int b): _a(a), _b(b) {
// }
A(int a): A(a, 0) {
}
void show() const {
cout << _a << " " << _b << endl;
}
void set(int a) {
_a = a;
}
};
int main(int argc, char* argv[]) {
A a;
A b(10);
int i = 20;
A c(i, 20);
c.set(i);
a.show();
b.show();
c.show();
cout << "Hello world!" << endl;
string file = "wangbing";
ifstream in(file);
vector<A> v;
v.emplace_back(10, 10);
v[0].show();
int x = 10;
cout << to_string(x) << endl;
string y = "-123.45";
size_t pos;
cout << stod(y, &pos) << " " << pos << endl;
return 0;
}
lamada表达式:值捕获获取const值(mutable 改变),后置返回值类型。使用[=],[&]隐式捕获(编译器推断需要捕获的变量,=为值捕获 &为引用)。[=, identifier_list][&, identifier_list]混合捕获
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
class A {
int _a = 10, _b = 10;
public:
A() = default;
void show() const {
cout << _a << " " << _b << endl;
}
void add(int a) {
_a += a;
}
int geta() const {
return _a;
}
};
int main(int argc, char* argv[]) {
vector<A> v = {A(), A(), A()};
for_each(v.begin(), v.end(), [](const A& a){ a.show(); });
vector<A> v2;
for_each(v.begin(), v.end(), [&v2](const A& a){ v2.push_back(a); });
for_each(v2.begin(), v2.end(), [](const A& a){ a.show(); });
int x = 10;
for_each(v.begin(), v.end(), [x](A& a)mutable { a.add(++x); }); //值传递默认const
for_each(v.begin(), v.end(), [](const A& a){ a.show(); });
int first = accumulate(v.begin(), v.end(), 0, [](int x, const A& y) -> int
{ if(y.geta() > 22) return x + y.geta(); else return x;});
cout << first << endl;
return 0;
}