C++核心技术:现代C++的一些重要改进
2 分钟阅读
•
114 字
+
292 词
字面量
#include <chrono>// std::chrono literals
#include <complex>// std::complex/complex literals
#include <iostream>// std::cout
#include <string>// std::string literals
#include <string view>// std::string view literals
#include <thread>//std::this thread::sleep for
using namespace std;
int main()
cout <<"i * i = " << 1i * 1i <<'\n';
cout<<"Waiting for 500ms\n";
this thread::sleep for(500ms);
cout<<"Hello world"s.substr(0,5)<<'\n';
cout<<"Hello world"sv.substr(6)<<'\n';
输出是:
i*i=(-1,0)
Waiting for 500ms
Hello
world
二进制使用 0b1110011
当需要使用枚举时,默认情况应该选择枚举类
enum class Color:uint8_t{red=1,green,blue};
时间库chrono
auto t1 = chrono::steady_clock::now();
cout<<"hello\n";
auto t2 = chrono::steady_clock::now();
cout<<(t2-t1)/1ns<<" ns has elapse\n";
c++20后的chrono
可以直接输出cout<<(t2-t1)
且可以直接输出system_clock::now() 输出的是UTC时间
随机数库random
#include <algorithm>// std::generate
#include <iostream>// std::cout
#include <random>// std::mt19937/random device/...
#include <vector>// std::vector
#include "ostream_range.h"// operator<< for ranges
using namespace std;
int main()
auto seed = random_device{}(); //生成随机种子
cout<<"Seed is "<< seed << '\n';
mt19937 engine{seed};//使用种子初始化随机引擎
uniform_int_distribution dist{1, 1000};
vector<int> v(100);
generate(v.begin(),v.end(),[&]{ return dist(engine);});
cout << v<< '\n';
}
使用shuffle替代shuffle_random
auto seed = random_device{}(); //生成随机种子
cout<<"Seed is "<< seed << '\n';
mt19937 engine{seed};//使用种子初始化随机引擎
vector<int> v(100);
iota(v.begin(),v.end(),1);
shuffle(v.begin(),v.end(),engine);