为什么在C++中从stdin读取行比在Python中慢?
大家好!我是一名C++初学者,遇到了一个奇怪的问题。我在Codeforces上解决一道需要从标准输入读取1000万个整数的题目。我用C++编写了代码,使用了std::cin和std::getline,但程序运行得非常慢——大约30秒。为了验证,我写了一个类似的Python脚本,使用普通的input()和sys.stdin.read().split(),它只用了3-4秒就完成了!这怎么可能?毕竟C++被认为是性能更高的语言。
以下是我的C++代码:
```cpp
#include
#include
#include
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::vector numbers;
std::string line;
while (std::getline(std::cin, line)) {
// 从字符串中解析数字
size_t pos = 0;
while (pos < line.size()) {
size_t next = line.find(' ', pos);
if (next == std::string::npos) next = line.size();