仅供快速复习,最佳方案还是遇到了查dash

string 常见操作

构造、长度容量、访问略

输入输出

1
2
3
string s;
cin >> s; // 读取一个单词(遇到空格停止)
getline(cin, s); // 读取整行(包括空格)

修改

  • 追加与连接 += append push_back
  • 插入与删除 s.insert(5,””) s.erase(5,6)//从5的位置删除6个字符
    s.replace(1,3,”xxx”)

子串操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//提取子串
string s = "Hello World";
string sub = s.substr(6, 5); // 从位置6开始,取5个字符 - "World"
string sub2 = s.substr(6); // 从位置6到结尾 - "World"

//查找
size_t pos = s.find("World"); // 6 - 第一次出现的位置
pos = s.find("Hello", 1); // 12 - 从位置1开始查找

// 反向查找
pos = s.rfind("Hello"); // 12 - 从后往前找

// 查找字符
pos = s.find_first_of("aeiou"); // 1 - 第一个元音字母 'e'
pos = s.find_last_of("aeiou"); // 15 - 最后一个元音字母 'o'
pos = s.find_first_not_of("Helo "); // 6 - 第一个不是这些字符的 'W'

比较

1
2
3
4
5
6
string s1 = "apple", s2 = "banana";

if (s1 == s2) { /* 相等 */ }
if (s1 != s2) { /* 不相等 */ }
if (s1 < s2) { /* s1 在字典序中小于 s2 */ }
if (s1.compare(s2) < 0) { /* 同上,返回负数、0或正数 */ }

数值转换

1
2
3
4
5
6
7
8
9
// 字符串转数值
string num_str = "123";
int i = stoi(num_str); // 转 int
double d = stod("3.14"); // 转 double
long l = stol("1000000"); // 转 long

// 数值转字符串
string s1 = to_string(123); // "123"
string s2 = to_string(3.14159); // "3.14159"

优先队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#include <queue> // 包含 priority_queue
#include <functional> // 包含 greater<T> 等函数对象

// 基本声明格式
std::priority_queue<T, Container, Compare> pq;
// 1. 默认构造函数(最大堆)
std::priority_queue<int> pq1;

// 2. 使用 vector 作为底层容器,默认比较函数 less<T>(最大堆)
std::priority_queue<int, std::vector<int>> pq2;

// 3. 创建最小堆
std::priority_queue<int, std::vector<int>, std::greater<int>> min_pq;

// 4. 使用自定义比较函数
struct Compare {
bool operator()(int a, int b) {
return a > b; // 最小堆
}
};
std::priority_queue<int, std::vector<int>, Compare> custom_pq;

// 5. 从已有容器初始化
std::vector<int> vec = {3, 1, 4, 1, 5};
std::priority_queue<int> pq3(vec.begin(), vec.end());

pq.push(10); // 插入元素,O(log n)
pq.emplace(20); // 原地构造元素,C++11,O(log n)

pq.top(); // 返回优先级最高的元素,O(1)
// 优先队列没有 front() 或 back()

pq.pop(); // 删除优先级最高的元素,O(log n)
pq.empty(); // 检查是否为空,O(1)
pq.size(); // 返回元素数量,O(1)


本站由 Zane Jiang 使用 Stellar 1.33.1 主题创建,一款很棒的 Hexo 主题!

总访问 次 || 本页访问
总访客 人 || 本页访客