前言
这里简单记录下
stl标准模板库
学习笔记
c++备忘
宏参数
#、##、##__VA_ARGS__
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16//可变参数宏
printf_log("%d-%d-%d\n", 2019, 11, 28);
PRINT("%d", 5);
int a1 = 1;
int a2 = 2;
ADD_TO_AN(1, 4);
ADD_TO_AN(2, 5);
printf("%d, %d", a1, a2);生成指定范围随机数
1
2
3
4用于
std::string
的格式化函数1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17static std::string string_format(const char* fmt, ...) {
std::string strRet;
if (nullptr != fmt) {
va_list args = nullptr;
va_start(args, fmt);
int nLength = _vsnprintf(nullptr, 0, fmt, args);
if (nLength > 0) {
std::unique_ptr<char> uptr(std::make_unique<char>(nLength + 1));
_vsnprintf(uptr.get(), nLength + 1, fmt, args);
strRet = uptr.get();
}
va_end(args);
}
return strRet;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20template<typename T>
using item_return = T&&;
template<typename T>
inline item_return<T> convert(T&& arg) {
return static_cast<T&&>(arg);
}
template<typename... Args>
std::string string_format(const char* format, Args&&... args) {
char buff[1024] = { 0 };
snprintf(buff, sizeof(buff), format, convert(std::forward<Args>(args))...);
return buff;
}
//for test demo
time_t t = time(NULL);
struct tm tm = { 0 };
localtime_s(&tm, &t);
std::string s = string_format("%d-%d-%d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
stl (Standard Template Library)
标准模板库 学习笔记
Source Code:
boost
: https://www.boost.org/users/download/sgi_stl
: cygnus C++ 2.91 for Windows安装于C:\cygnus,所有头文件置于C:\cygnus\cygwin-b20\include\g++下共128个文件pj_stl
: pj版本被Visual C++采用,所以可以在Visual C++的include子目录下(如: C:\xxx\VC\include)找到所有头文件
容器分类:
- 顺序容器(元素排序取决于插入顺序)
vector, deque, list, forward_list, array, string
- 关联容器(元素排序取决于内部规则)
set, map, multiset, multimap
- 无序关联容器
unordered_set, unordered_map, unordered_multiset, unordered_multimap
- 容器适配器(可自定义底层数据结构)
stack, queue, priority_queue(优先级队列)
容器迭代器:
- 随机访问迭代器
vector, deque, array
- 双向迭代器
list, set, map, multiset, multimap, unordered_set, unordered_map, unordered_multiset, unordered_multimap
- 前向迭代器
forward_list
- 无迭代器
stack, queue, priority_queue
vector
向量
头文件:#include <vector>
特性:
- 常用作数组的替代品
- 允许尾部直接插入删除
- 允许下标随机访问
- 常用的内部实现是动态数组
常用操作:
1 | std::vector<T> v; |
list
链表
头文件:#include <list>
特性:
- 允许头部/尾部的直接插入/删除
- 不允许下标访问
- 常用的内部实现是双向链表
常用操作:
1 | std::list<T> l; |
tuple
元组
头文件:#include <tuple>
特性:
- c++11 新增
- 捆绑N个类型的数据
- 常用std::make_tuple构造
- 可用于函数返回多个结果
常用操作:
1 | auto t = std::make_tuple(a, b, c); |
示例:
1 | int a = 0; |
1 | int a = 0; |
小技巧
加括号避免与宏定义冲突
- 常用的最小/最大运算
(max/min)
:- 头文件:
#include <algorithm>
方法1:
1 | int x = 100; |
方法2:(该方法必须事先知道,x和y的类型,且二者类型一致)
1 | int x = 100; |