使用XML字符串填充双精度数对的向量
Fill vector of pairs of doubles using XML string
我有一个XML字符串,如下所示:
< thing TYPE="array" UNITS="meters">1.0,1.3,1.2,1.7,1.4,1.9< /thing>
我试着把每对数字放入一个std::vector< std::pair< double,double > >
。完成后应该是这样的:
& lt;(1.0,1.3), (1.2,1.7), (1.4,1.9)>
我知道我可以做到这一点的一种方法是搜索字符串中的每个逗号以找到单个数字并创建子字符串,然后将子字符串转换为双精度并填充对中的一个数字。然而,这似乎是一种过于复杂的方式来完成这项任务。有没有一种简单的方法,比如用std::istringstream
?提前感谢!
使用getline()
如何?
#include <vector>
#include <sstream>
#include <iostream>
int main()
{
std::vector<std::pair<double, double>> vpss;
std::string str1, str2;
std::istringstream iss("1.0,1.3,1.2,1.7,1.4,1.9");
while ( std::getline(iss, str1, ',') && std::getline(iss, str2, ',') )
{
std::cout << str1 << ", " << str2 << std::endl;
vpss.emplace_back(std::stod(str1), std::stod(str2));
}
return 0;
}
另一种解决方案是将逗号放在char
变量
#include <vector>
#include <sstream>
#include <iostream>
int main()
{
std::vector<std::pair<double, double>> vpss;
char ch;
double d1, d2;
std::istringstream iss("1.0,1.3,1.2,1.7,1.4,1.9");
while ( iss >> d1 >> ch >> d2 )
{
std::cout << d1 << ", " << d2 << std::endl;
vpss.emplace_back(d1, d2);
iss >> ch;
}
return 0;
}
您可以使用regex来捕获您想要的数据,并使用std::stringstream
来解析它
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <regex>
#include <utility>
using namespace std;
int main()
{
auto xml_str = R"(< thing TYPE="array" UNITS="meters">1.0,1.3,1.2,1.7,1.4,1.9< /thing>)"s;
auto r = regex(R"(>(d.*d)<)"s);
auto m = smatch{};
auto vec = vector<pair<double, double>>{};
// Determine if there is a match
auto beg = cbegin(xml_str);
while (regex_search(beg, cend(xml_str), m, r)) {
// Create a string that holds the 1st capture group
auto str = string(m[1].first, m[1].second);
auto ss = stringstream{str};
auto token1 = ""s;
auto token2 = ""s;
auto d1 = double{};
auto d2 = double{};
// Parse
while (getline(ss, token1, ',')) {
getline(ss, token2, ',');
d1 = stod(token1);
d2 = stod(token2);
vec.emplace_back(make_pair(d1, d2));
}
// Set new start position for next search
beg = m[0].second;
}
// Print vector content
auto count = 1;
for (const auto& i : vec) {
if (count == 3) {
cout << "(" << i.first << ", " << i.second << ")n";
count = 1;
}
else {
cout << "(" << i.first << ", " << i.second << "), ";
count++;
}
}
}
(Compile with -std=c++14
)
输出:(1, 1.3), (1.2, 1.7), (1.4, 1.9)
现场演示
相关文章:
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 从.txt文件读取到C++中的双精度向量
- C++ 运算符"="重载 - 在 lhs 上获取向量中的所有值,使其等于 rhs 上的双精度值
- 使用整数初始化列表初始化长双精度的向量
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 向量<对<双精度,双精度>>给出问题
- 获取长双精度向量的方差
- 如何将 4 个浮点数的 ps 向量转换为 4 个双精度并存储到 pd 数组
- 双精度/整数模板函数的向量
- 模板:如何泛化输入以接收整数、双精度或特定(模板)容器的向量
- 如何从二进制文件中读取双精度并将其保存在向量中
- C++在向量中添加元素的双精度
- 对双精度和指针对的向量进行排序
- 通过更改代码格式来计算结构向量中包含的双精度变量的平均值的不同结果?
- 以最大性能将双精度的向量截断为单精度
- 将值存储到具有相同精度C++的双精度向量中
- 如何从双精度向量的向量访问数据
- 从十六进制数组读取双精度到向量
- C++ 将字符串向量转换为给定.dat文件中的双精度向量
- <double> 向量被转换为向量<双精度,分配器<double>>