C++读取一个数学函数并进行排序

C++ reading a mathematical function and sorting

本文关键字:函数 排序 一个 读取 C++      更新时间:2023-10-16

我正在从一个格式为f(x,y,f(x),g)的文件中读取一个函数,一旦我读取了输入,它就被存储为一个向量,我试图获取逗号之间的每个值,所以在这种情况下,我想将x,y f(x)和g作为单独的字符/字符串。我被卡住了,有什么想法吗?

这是我提出的解决方案:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
//Split string into vector of strings
vector<string> split(string str, char delimiter) 
{
  vector<string> internal;
  stringstream ss(str); // Turn the string into a stream.
  string tok;
  while(getline(ss, tok, delimiter)) 
  {
    internal.push_back(tok);
  }
  return internal;
}
int main()
{
  string myInput = "f(x,y,f(x),g)";
  //Extract the string between outer brackets
  size_t startIndex = myInput.find_first_of("(") + 1;
  size_t endIndex   = myInput.find_last_of(")");
  string innerStr   = myInput.substr(startIndex, endIndex-startIndex);
  //Split the result by comma
  vector<string> sep = split(innerStr, ',');
  for(unsigned int i = 0; i < sep.size(); ++i)
  {
     cout << sep[i] << endl;
  }
}

希望它能帮助