生成随机数

#include <ctime>using namespace std; int main() { srand((unsigned int)time(NULL)); cout << rand() % 40 << endl; return 0; }

January 16, 2022 · 1 min · Rick Cui

deque 容器

deque 容器的空间不用手动收缩,类内部会自动处理

January 16, 2022 · 1 min · Rick Cui

巧妙收缩 vector 空间

resize() 或者 erase() 后 vector 的空间大小不会自动减小 int main() { vector<int> v; for(int i = 0; i < 100000; ++i){ v.push_back(i); } cout << "size: " << v.size() << endl; cout << "capacity: " << v.capacity() << endl; cout << "-----------------------" << endl; v.resize(10); cout << "size: " << v.size() << endl; cout << "capacity: " << v.capacity() << endl; cout << "-----------------------" << endl; vector<int>(v).swap(v); cout << "size: " << v....

January 16, 2022 · 1 min · Rick Cui

vector 中的元素存放在堆上还是栈上

结论 allocator 分配器是定义内存模型的类,用于标准库的某些部分,尤其是 STL 容器,如果所有标准容器的最后一个(可选)模板参数没有指定,那么它将使用这个分配器,并且它是标准库中唯一一个预定义的分配器 vector 中存放的如果是对象类型,则会通过 allocator 在堆上开辟足够的空间来存放和管理集合中的对象 vector 中存放指针类型,一定要记得手动释放内存 存放对象 class Person{ public: Person(int age, int id){ m_age = age; m_id = id; cout << "Person(int, int)..." << endl; } Person(const Person& p){ m_age = p.m_age; m_id = p.m_id; cout << "Person(const Person& p)..." << endl; } ~Person(){ cout << "~Person()..." << endl; } void* operator new(size_t size){ void* p = malloc(size); cout << "new()..." << endl; return p; } void operator delete(void *p){ cout << "delete()....

January 16, 2022 · 3 min · Rick Cui

STL Hello World

平时要有容器、算法、迭代器的思维模式 容器提供迭代器,算法使用迭代器 // 算法 int count(int* begin, int* end, int val){ int n = 0; while(begin != end){ if(*begin == val){ n++; } begin++; } return n; } int main() { // 容器 int arr[] = {1, 3, 0, 5, 1, 3, 1, 0}; // 迭代器 int* begin = arr; int* end = *(&arr + 1); int n = count(begin, end, 1); cout << "count: " << n << endl; return 0; }

January 16, 2022 · 1 min · Rick Cui