date: 2025-04-11
title: Cpp-STL-Crash
status: DONE
author:
- AllenYGY
tags:
- cpp
- vector
- string
- priority
- unordered_map
publish: false
Cpp-STL-Crash
vector
(万能动态数组)vector<int> v; // 声明
v.push_back(3); // 尾部插入
v.pop_back(); // 尾部删除
v.size(); // 元素个数
v[0] = 5; // 随机访问(不检查越界)
sort(v.begin(), v.end()); // 排序
string
(字符串处理)string s = "abc"; // 拼接
s += "def"; // 拼接
s.substr(1, 2); // 取子串 (位置, 长度)
s.find("cd"); // 查找 (返回位置)
s.replace(1, 2, "xy"); //从位置 1 开始,长度为 2 的子串替换为 "xy"
stoi(s); // 字符串转数字
priority_queue
(优先队列/堆)priority_queue<int> pq; // 默认大根堆
pq.push(3); // 插入
pq.top(); // 取堆顶
pq.pop(); // 弹出堆顶
// 小根堆定义
priority_queue<int, vector<int>, greater<int>> min_pq;
// 自定义
struct Point {
int x, y;
int distance() const {
return x * x + y * y;
}
};
// 自定义比较函数,用于小根堆
struct ComparePoint {
bool operator()(const Point& p1, const Point& p2) const {
return p1.distance() > p2.distance();
}
};
priority_queue<Point, vector<Point>, ComparePoint> pq_points;
unordered_map
(哈希表)unordered_map<string, int> mp;
mp["apple"] = 5; // 插入/修改
mp.count("apple"); // 判断是否存在
mp.erase("apple"); // 删除
for (auto &[k, v] : mp) // 遍历(C++17)
cout << k << " " << v;
unordered_map<string, int> umap; //定义
umap.insert(Map::value_type("test", 1));//增加
//根据key删除,如果没找到n=0
auto n = umap.erase("test") //删除
auto it = umap.find(key) //改
if(it != umap.end())
it->second = new_value;
//map中查找x是否存在
umap.find(x) != map.end()//查
//或者
umap.count(x) != 0
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <bitset>
#include <string>
int main() {
// 1. set 操作
set<int> mySet = {1, 3, 5, 7};
mySet.insert(9);
cout << "Set elements: ";
for (int element : mySet) {
cout << element << " ";
}
cout << endl;
// 2. bitset 操作
bitset<8> myBitset(10); // 用整数 10 初始化 8 位的 bitset
cout << "Original bitset: " << myBitset << endl;
myBitset.set(3); // 设置第 3 位为 1
cout << "Bitset after set(3): " << myBitset << endl;
myBitset.reset(1); // 重置第 1 位为 0
cout << "Bitset after reset(1): " << myBitset << endl;
// 3. unordered_map 操作及将键值对存入 vector
unordered_map<string, int> myMap = {
{"apple", 5},
{"banana", 3},
{"cherry", 7}
};
vector<pair<string, int>> myVector(myMap.begin(), myMap.end());
cout << "Vector elements (from unordered_map):" << endl;
for (const auto& pair : myVector) {
cout << "Key: " << pair.first << ", Value: " << pair.second << endl;
}
return 0;
}