欢乐C++ —— 17. 标准库特殊设施
tuple
类似与pair,tuple 可以有任意数量的成员。当我们想将一些数据简单组合在一起,又不想定义新的数据结构,那么此时使用 tuple 定义在头文件
#include <iostream>
#include <algorithm>
#include <tuple>
using namespace std;
int main( ) {
//两种初始化方式
tuple<int, int, int> t1(1, 2, 3);
auto t2 = make_tuple(1, 2, 3);
t1 == t2; t1 < t2; //比较运算 必须成员数量相同
get<0>(t1); get<1>(t1); get<2>(t1); //获取t1 中第 i 个元素的引用
tuple_element<0, decltype( t1 )>::type i; //获取第t1 中 第 0 个元素的类型
i = tuple_size<decltype( t1 )>::value; //获取第 t1 中元素个数
return 0;
}
bitset
创建
有多种创建方法,经典的两种:
- 从给定数字创建
- 从字符串创建
int main( ) {
bitset<32> bset1(0xffffffff);
string s = "cacaccca";
bitset<9> bset2(s, 0, s.size( ), 'c', 'a');
// 从s, 0下标开始,s.size()结束, 'c'识别为0,‘a' 识别为1
cout<<bset2.to_string('9','2'); //0转为'9' 1转为’2‘
return 0;
}
有用的方法
#include <bitset>
#include <string>
#include <iostream>
using namespace std;
int main( ) {
bitset<32> bset1(0xffffffff);
string s = "cacaccca";
bitset<9> bset2(s, 0, s.size( ), 'c', 'a');
cout << bset2.to_string( );
//将c 识别为0 a识别为1
bset2.any( ); //是否有置位
bset2.all( ); //是否所有位都置位
bset2.none( );//是否所有位都没有置位
bset2.count( );//置位的个数
bset2.size( );//位总数
bset2.set( );//所有置位
bset2.set(1);//将1置位
bset2.set(1, false);//将1取消置位
bset2.reset( );//所有位取消置位
bset2.reset(1);//1取消置位
bset2.flip( );//所有位反转
bset2.flip(1);//1位反转
bset2.test(1);//若1置位则返回true
cout<<bset2[1];//访问1处的位
cout<<bset2.to_string( );//默认是 '0' '1'
cout<<bset2.to_string('a', 'c'); //分别将0 1转化为'a' 'c'
cin >> bset2;//按'0' '1' 读入
cout << bset2;//按 '0' '1' 输出
return 0;
}
正则表达式
C++ 正则表达式库
随机数
由于使用普通的rand 是伪随机数,并且不好生成浮点随机数等,所以C++在头文件
彩蛋:欢乐C++ 系列全部结束~!!共17节,覆盖大约《C++ Primer》 这本书80%的内容。接下来打算做一个局域网传输的小工具,可能会先看看设计模式。就这,今后也要加油啊!! 2020.7.6