gpt4 book ai didi

c++ - 闯入 vector

转载 作者:行者123 更新时间:2023-11-30 05:42:08 25 4
gpt4 key购买 nike

我想将数学表达式拆分为 vector ,这样我就可以应用后缀表示法来求解方程。我在 Internet 上找到了这个,但输出有点滑稽。我不能使用 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 这样的序列分别推送到 vector (如果它不仅仅是空格),然后推送分隔符。

关于c++ - 闯入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30801155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com