使用XML字符串填充双精度数对的向量

Fill vector of pairs of doubles using XML string

本文关键字:向量 双精度 XML 字符串 填充 使用      更新时间:2023-10-16

我有一个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)

现场演示