动态规划--线性dp
一、数字排列2.数字排列 - 蓝桥云课
stringstream流的使用
一、基础概念与初始
stringstream
是C++标准库中定义于<sstream>
头文件的类,用于在内存中实现字符串与数据类型的双向转换。
。其特点包括:
- 初始化方式:
// 直接构造 std::stringstream ss("初始内容"); // 通过str()方法赋值 ss.str("新的字符串");
- 子类区别:
istringstream
:仅支持输入操作(从字符串读取数据)ostringstream
:仅支持输出操作(向字符串写入数据)stringstream
:支持双向操作
二、核心操作与数据转换
1. 数据写入与提取
- 写入数据(数值→字符串):使用
<<
操作符,支持所有基本数据类型==int age = 25; ss << "姓名: 张三 年龄: " << age;
- 提取数据(字符串→数值):使用
>>
操作符,自动跳过空白字符std::string name; int extracted_age; ss >> name >> extracted_age; // 按空格分隔提取
2. 数据类型转换
- 字符串→数值:
std::string str = "123.45"; double num; ss << str; ss >> num; // num = 123.45
- 数值→字符串:
int val = 42; ss << val; std::string s = ss.str(); // s = "42"
- 多次转换需重置状态:
ss.clear(); // 清除错误标志 ss.str(""); // 清空缓冲区内容[4,6](@ref)
三、高级字符串处理
1. 字符串拼接
std::ostringstream oss;
oss << "ID: " << 1001 << " 分数: " << 98.5;
std::string result = oss.str(); // "ID: 1001 分数: 98.5"
2. 带分隔符的解析
std::string data = "apple,15,3.99";
std::string item;
int quantity;
float price;// 替换逗号为空格
std::replace(data.begin(), data.end(), ',', ' ');
std::stringstream ss(data);
ss >> item >> quantity >> price;
四、代码实现
#include <bits/stdc++.h>
using namespace std;
vector<string> dp(20);
vector<int> a[100010];
int main()
{int n;dp[0] = "20";for(int i=1; i<=16; i++)dp[i] += dp[i-1] + ' ' + to_string(20-i) + ' ' + dp[i-1];cin >> n;stringstream ss(dp[16]); //将ss初始化为dp【16】for(int i=0; i<n; i++){int a;ss >> a; //从ss流中提取一个整数到变量acout << a << ' ';}/*spite的实现,提取由空格隔开的字符串int ans = 1,index=0;while(ans <= n){while(dp[16][index]!=' ') cout << dp[16][index++];cout << " ";index++;ans++;}*/return 0;
}