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

时间:2022-08-11 19:24:42
 ------------------------------------------------------------------------------
#include <vector>
#include <algorithm>
#include <random> int main()
{
std::vector<int> a{, , , , , , , , , , };
std::vector<int> b(); std::sample(a.begin(), a.end(),
b.begin(), b.size(),
std::mt19937{std::random_device{}()});
return ;
}
------------------------------------------------------------------------------
#include <iostream>
#include <string> int main()
{
const std::string myString = "Hello World"; // C++17 with init if:
if (const auto it = myString.find("Hello"); it != std::string::npos)
std::cout << it << " Hello\n"; if (const auto it = myString.find("World"); it != std::string::npos)
std::cout << it << " World\n";
}
------------------------------------------------------------------------------
#include <iostream>
#include <string> using namespace std; template<typename ...Args> auto sum(Args ...args)
{
return (args + ... + );
} template<typename ...Args> auto sum2(Args ...args)
{
return (args + ...);
} int main()
{
cout << sum(, , , , , , ) << "\n";
cout << sum2(, , , , , , ) << "\n";
}
------------------------------------------------------------------------------
#include <utility>
#include <tuple>
#include <iostream> int main() {
std::pair d(, 0.0);
std::tuple t(, , ); std::cout << std::get<>(t) << ", " << std::get<>(t) << ", " << std::get<>(t) << "\n";
}
------------------------------------------------------------------------------
#include <iostream>
#include <string> struct S
{
int n;
std::string s;
float d;
}; template <std::size_t I>
auto& get(S& s)
{
if constexpr (I == )
return s.n;
else if constexpr (I == )
return s.s;
else if constexpr (I == )
return s.d;
} int main()
{
S obj { , "hello", 10.0f };
std::cout << get<>(obj) << ", " << get<>(obj) << "\n";
}
------------------------------------------------------------------------------
https://www.codingame.com/playgrounds/2205/7-features-of-c17-that-will-simplify-your-code/introduction
------------------------------------------------------------------------------