我得到一个由逗号分隔的 n 个整数的输入字符串(例如“23,4,56”)。我需要设置一个字符串流来表示这个字符串,然后用它将每个整数扫描成一个向量。向量的元素(列表中的整数)最终将逐行输出。我得到了 main(),并且只负责编写 parseInts(string str)。出于某种原因,我一直在超时。我猜这是我的 while 循环中的一些东西,特别是关于我如何使用 str() 操作我的 sstream,但我无法弄清楚到底发生了什么。我是 sstream 和 C++ 的新手,所以任何帮助都将不胜感激!
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
vector<int> parseInts(string str) {
int a; //will use this to hold the value of the 1st int in the sstream
stringstream list_initial; //will iterate over this sstream
list_initial.str(str); //set sstream to represent input str
vector<int> list_final; //will return this final vector for output in main
while (!list_initial.str().empty()){ //stop iterating at end of string
list_initial>>a; //store leading int value in a
list_final.push_back(a); //add a to end of vector
while (!ispunct(list_initial.str()[0])){ //get to next int in list
list_initial.str(list_initial.str().erase(0,1));
};
list_initial.str(list_initial.str().erase(0,1)); //erase leading comma
};
return list_final;
};
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}