문자열에서 문자열로 이동하여 벡터로
-
19-08-2019 - |
문제
이 샘플 프로그램은 응용 프로그램에서 구현하고 싶은 단계입니다. 문자열의 int 요소를 별도로 벡터로 밀고 싶습니다. 내가 어떻게 할 수있는?
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main(){
string line = "1 2 3 4 5"; //includes spaces
stringstream lineStream(line);
vector<int> numbers; // how do I push_back the numbers (separately) here?
// in this example I know the size of my string but in my application I won't
}
해결책
int num;
while (lineStream >> num) numbers.push_back(num);
다른 팁
이것은 전형적인 예입니다 std::back_inserter
.
copy(istream_iterator<int>(lineStream), istream_iterator<int>(),
back_inserter(numbers));
원하는 경우 시작부터 바로 벡터를 만들 수 있습니다.
vector<int> numbers((istream_iterator<int>(lineStream)),
istream_iterator<int>());
첫 번째 논쟁 주위에 괄호를 두는 것을 잊지 마십시오. 컴파일러는 그렇지 않으면 함수 선언이라고 생각합니다. 숫자의 반복자를 얻기 위해 벡터를 사용하는 경우 IsTream Iterator를 직접 사용할 수 있습니다.
istream_iterator<int> begin(lineStream), end;
while(begin != end) cout << *begin++ << " ";
제휴하지 않습니다 StackOverflow