/ / Parsowanie liczb całkowitych ze STL - c ++, parsowanie, stl

Analizowanie liczb całkowitych za pomocą STL - c ++, parsowanie, stl

Oto piękny sposób na analizowanie int i przechowywanie ich w wektorze, o ile są one ograniczone spacją (od Podziel ciąg w C ++?):

#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

int main() {
using namespace std;

string s = "3 2 1";
istringstream iss(s);
vector<int> tokens;

copy(istream_iterator<int>(iss),
istream_iterator<int>(),
back_inserter<vector<int> >(tokens));
}

Czy możliwe jest określenie innego ogranicznika (np. ",") Przy zachowaniu czegoś podobnego?

Odpowiedzi:

1 dla odpowiedzi № 1

Możesz uogólnić podział na łańcuchy używając wyrażenia regularnego (C ++ 11). Ta funkcja blokuje twój ciąg znaków, dzieląc go na wyrażenie regularne.

vector<string> split(const string& input, const regex& regex) {
sregex_token_iterator
first(input.begin(), input.end(), regex, -1),
last;
return vector<string>(first, last);
}

Na przykład, aby podzielić na "," przekazać regex(",") do funkcji.

#include <iostream>
#include <string>
#include <regex>
#include <vector>

using namespace std;

vector<string> split(const string& input, const regex& regex) {
sregex_token_iterator
first(input.begin(), input.end(), regex, -1),
last;
return vector<string>(first, last);
}

int main() {

const regex r = regex(",");
const string s = "1,2,3";

vector<string> t = split(s, r);
for (size_t i = 0; i < t.size(); ++i) {

cout << "[" << t[i] << "] ";
}
cout << endl;

return 0;
}