闯入矢量
break in to vector
本文关键字:闯入 更新时间:2023-10-16
我想将数学表达式拆分为向量,以便我可以应用后缀符号来求解方程。我在互联网上发现了这个,但输出有点有趣。我不能使用 split
方法,因为它从结果中删除了分隔符。
3+cos(2)+2+1
我的预期输出是:
3
+
cos
(
2
)
+
2
+
1
但我得到的是这样的:
3+
cos(
2)
+
2+
1
我该如何解决这个问题?
这是我的代码:
vector<string> split(string& stringToSplit)
{
vector<string> result;
size_t pos = 0, lastPos = 0;
while ((pos = stringToSplit.find_first_of("+-*/()", lastPos)) != string::npos)
{
string value = stringToSplit.substr(lastPos, pos-lastPos+1);
result.push_back(value);
lastPos = pos+1;
}
result.push_back(stringToSplit.substr(lastPos));
return result;
}
int main()
{
string z = "3+cos(2)+2+1";
vector<string> d = split(z);
for(int i=0;i<d.size();i++)
{
cout<<d[i]<<endl;
}
getch();
return 0;
}
这可能
对你有用:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::vector<std::string> split(std::string &stringToSplit)
{
std::vector<string> result;
size_t pos = 0, lastPos = 0;
while((pos = stringToSplit.find_first_of("+-*/()", lastPos)) != string::npos)
{
string value = stringToSplit.substr(lastPos, pos - lastPos);
if(std::any_of(value.begin(), value.end(), [](char c) { return c != ' '; }))
result.push_back(value); // or you should trim the whitespaces instead and check whether value is not empty
result.push_back(stringToSplit.substr(pos, 1));
lastPos = pos + 1;
}
result.push_back(stringToSplit.substr(lastPos)); // the same trimming and check should be performed here
return result;
}
int main()
{
std::string z = "3+cos(2)+2+1";
std::vector<string> d = split(z);
for(unsigned int i = 0; i < d.size(); i++)
std::cout << d[i] << std::endl;
std::cin.get();
return 0;
}
代码将像cos
这样的序列分别推送到向量(如果它不仅是空格),然后推送分隔符。
相关文章: