算法随笔
ranges:sort
是sort的更安全好用的版本,但是太新,C++20,不用管,只记sort用法即可。
stringstream
std::stringstream 是字符串的“流(stream)”,可以把字符串当成输入/输出流进行读写。作用类似 cin / cout,但作用对象是字符串。
头文件:#include <sstream>
- 按空格自动分割字符串
string s = "10 20 hello 99";
stringstream ss(s);
string x;
while (ss >> x) {
cout << x << "\n";
}
自动按 空格 / Tab / 换行 分割。
- 字符串转数字
string s = "123";
stringstream ss(s);
int x;
ss >> x; // x = 123
比 stoi() 更稳健,不会抛异常。
- 解析一行多个字段
string line = "MESSAGE 10 id1 id0";
stringstream ss(line);
string type;
int time;
string rest;
ss >> type >> time; // 前两个字段
getline(ss, rest); // 剩余部分一整段读出
- 拼接字符串
stringstream ss;
int a = 10;
string b = "abc";
ss << "value: " << a << " " << b;
string res = ss.str(); // 取结果
效果和 cout 类似。
- 清空 stringstream(必须两步)
ss.str(""); // 清空内容
ss.clear(); // 清空状态位(否则下次读取失败)
这两行必须一起写。
- 将容器序列化为字符串
vector<string> v = {"a", "b", "c"};
stringstream ss;
for (auto &x : v) ss << x << " ";
string res = ss.str(); // "a b c "
应用:leetcode3433等

浙公网安备 33010602011771号