数量不定的参数模板
void print() { } //...就是pack(包) template<typename T, typename... Types> //print(7.5,"hello",bitset<16>(377),42); ...部分就是{"hello",bitset<16>(377),42} void print(const T& firstArg, const Types&... args) { //sizeof...(args)是args参数的个数 cout << sizeof...(args) << " "; cout << firstArg << endl; print(args...); } /*template<typename... Types> void print(const Types&... args) { cout << sizeof...(args) << " "; }*/ int main() { print(7.5, "hello", (377), 42); cout << endl; return 0; }
lambda函数
int a = 123; auto f = [a] { cout << a << endl; }; f(); // 输出:123 //或通过“函数体”后面的‘()’传入参数 auto x = [](int a) { cout << a << endl; }; x(123); cout << endl;
initializer_list
void print(initializer_list<int> vals) { for (auto p = vals.begin(); p != vals.end(); p++) { cout << *p << "\n"; } cout << endl; } int main() { print({ 10,5,2,29,30,55,2 }); cout << endl; return 0; }
初始化列表和普通构造函数
class P { public: P(int a, int b) { cout << "P(int,int), a=" << a << ",b=" << b << endl; } P(initializer_list<int>initial) { cout << "P(initalizer_list<int>,values="; for (auto i : initial) { cout << i << " "; } cout << endl; } }; int main() { P p(55, 7); P q{ 9,20 }; P r{ 4, 29, 66 }; P s = { 99, 10 }; cout << endl; return 0; } /* cout: P(int,int), a=55,b=7 P(initalizer_list<int>,values=9 20 P(initalizer_list<int>,values=4 29 66 P(initalizer_list<int>,values=99 10 */
explicit
class P { public: P(int a, int b) { cout << "P(int a, int b)\n"; } P(initializer_list<int>) { cout << "P(initializer_list<int>)\n"; } explicit P(int a, int b, int c) { cout << "explicit P(int a, int b, int c)\n"; } }; void fp(const P&) { }; int main() { P p1{ 77, 5 }; P P2{ 77, 5 }; P p3{ 77, 5, 42 }; P p4 = { 77, 5 }; P p5 = { 77, 5, 42 }; P p6(77, 5, 42); cout << endl; fp({ 47, 11 }); fp({ 47,11,3 }); fp(P{ 47,11 }); fp(P{ 47,11,3 }); cout << endl; P p11{ 77, 4, 42, 500 }; P p12 = { 77,5,42,500 }; P p13{ 10 }; cout << endl; return 0; } /* cout P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) explicit P(int a, int b, int c) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) P(initializer_list<int>) */
for循环的容器表达式
vector<double> vec{ 2, 3, 4, 5, 6, 7, 8}; for (auto elem : vec) { cout << elem << endl; } cout << endl; for (auto& elem : vec) { elem *= 3; } for (auto elem : vec) { cout << elem << endl; } /*output 2 3 4 5 6 7 8 6 9 12 15 18 21 24 */
day-11 代码
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240825082459112-376424429.jpg)