需要减少我的C++代码的执行时间

Need to reduce the execution time of my C++ code

本文关键字:代码 执行时间 C++ 我的      更新时间:2023-10-16

所以我需要编写一个程序来总结控制台输入中的数字。数字可以嵌入字符串中(例如 hello134 或 hi -12(。这是运行良好但超过时间限制(>1s(的代码。

那么,如何减少执行时间呢?这是我的程序未能通过的测试:https://pastebin.com/HNL9Vz7E

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
string line;
long p = 0;
int i = 0;
int b, e;
long long sum = 0;
while (getline(cin, line))
{
for (int i = 0; i < line.size(); i++)
{
if (isdigit(line[i]) || line[i] == '-' && isdigit(line[i + 1]))
{
b = i;
while (isdigit(line[++i]))
{}
e = i;
p = stoi(line.substr(b, b - e));
sum += p;
}
}
}
cout << sum << endl;
return 0;
}

可能是

line.substr(b, b - e)

我认为应该是

line.substr(b, e - b)

相反。它总是复制这一行中的大字符串。 使用该示例文件需要不到一毫秒的时间,但与未更改代码的一秒也相去甚远。而且:正则表达式比按自己的方式做要慢得多。