c++17 代码你能看懂吗?

 1 ------------------------------------------------------------------------------
 2 #include <vector>
 3 #include <algorithm>
 4 #include <random>
 5 
 6 int main()
 7 {
 8     std::vector<int> a{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 9     std::vector<int> b(5);
10 
11     std::sample(a.begin(), a.end(), 
12                 b.begin(), b.size(),
13                 std::mt19937{std::random_device{}()});
14     return 0;
15 }
16 ------------------------------------------------------------------------------
17 #include <iostream>
18 #include <string>
19 
20 int main()
21 {
22     const std::string myString = "Hello World";
23 
24     // C++17 with init if:
25     if (const auto it = myString.find("Hello"); it != std::string::npos)
26         std::cout << it << " Hello\n";
27 
28     if (const auto it = myString.find("World"); it != std::string::npos)
29         std::cout << it << " World\n";
30 }
31 ------------------------------------------------------------------------------
32 #include <iostream>
33 #include <string>
34 
35 using namespace std;
36  
37 template<typename ...Args> auto sum(Args ...args) 
38 { 
39     return (args + ... + 0); 
40 }
41 
42 template<typename ...Args> auto sum2(Args ...args) 
43 { 
44     return (args + ...);
45 }
46 
47 int main()
48 {
49     cout << sum(1, 2, 3, 4, 5, 6, 7) << "\n";
50     cout << sum2(1, 2, 3, 4, 5, 6, 7) << "\n";
51 }
52 ------------------------------------------------------------------------------
53 #include <utility>
54 #include <tuple>
55 #include <iostream>
56 
57 int main() {
58     std::pair d(0, 0.0);
59     std::tuple t(1, 2, 3);
60 
61     std::cout << std::get<0>(t) << ", " << std::get<1>(t) << ", " << std::get<2>(t) << "\n";
62 }
63 ------------------------------------------------------------------------------
64 #include <iostream>
65 #include <string>
66 
67 struct S 
68 {
69     int n;
70     std::string s;
71     float d;
72 };
73 
74 template <std::size_t I>
75 auto& get(S& s)
76 {
77     if constexpr (I == 0)
78         return s.n;
79     else if constexpr (I == 1)
80         return s.s;
81     else if constexpr (I == 2)
82         return s.d;
83 }
84 
85 int main()
86 {
87     S obj { 0, "hello", 10.0f };
88     std::cout << get<0>(obj) << ", " << get<1>(obj) << "\n";
89 }
90 ------------------------------------------------------------------------------
91 https://www.codingame.com/playgrounds/2205/7-features-of-c17-that-will-simplify-your-code/introduction
92 ------------------------------------------------------------------------------

 

转载于:https://www.cnblogs.com/nlsoft/p/10580521.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值