【发布时间】:2016-10-06 12:29:18
【问题描述】:
所以给出定义:
typedef char Task;
struct Tache {
char step;
int duration;
list<Task> precedentTask;
};
我为Tache写了一个提取操作符:
istream& operator>>(istream& lhs, Tache& rhs) {
string line;
getline(lhs, line, '\n');
stringstream ss(line);
ss >> rhs.step;
ss.ignore(numeric_limits<streamsize>::max(), '(');
ss >> rhs.duration;
ss.ignore(numeric_limits<streamsize>::max(), ')');
const regex re("\\s*,\\s*([a-zA-Z])");
string precedentTasks;
getline(ss, precedentTasks);
transform(sregex_token_iterator(cbegin(precedentTasks), cend(precedentTasks), re, 1), sregex_token_iterator(), back_insert_iterator<list<Task>>(rhs.precedentTask), [](const string& i) {
return i.front();
});
return lhs;
}
但是,当我尝试将此提取运算符与 istream_iterator 一起使用时,precedentTask 成员似乎会渗入下一个元素。例如,给定:
stringstream seq("A(3)\nB(4),A\nC(2),A\nE(5),A\nG(3),A\nJ(8),B,H\nH(7),C,E,G\nI(6),G\nF(5),H");
list<Tache> allTaches{ istream_iterator<Tache>(seq), istream_iterator<Tache>() };
for (const auto& i : allTaches) {
cout << i.step << ' ' << i.duration << ' ';
copy(cbegin(i.precedentTask), cend(i.precedentTask), ostream_iterator<Task>(cout, " "));
cout << endl;
}
我得到:
A 3
B 4 A
C 2 A A
E 5 A A A
G 3 A A A A
J 8 A A A A B H
H 7 A A A A B H C E G
我 6 A A A A B H C E G G
F 5 A A A A B H C E G G H
而不是我的预期:
A 3
B 4 A
C 2 A
E 5 A
G 3 A
J 8 B H
H 7 C E G
我 6 G
F 5 H
我是否误用了sregex_token_iterator?
【问题讨论】:
标签: c++ regex list iterator istream-iterator