0

所以给出定义:

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_iteratorprecedentTask成员似乎会渗入下一个元素。例如,给定:

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;
}

Live Example

我正进入(状态:

A 3
B 4 A
C 2 AA
E 5 AAA
G 3 AAAA
J 8 AAAABH
H 7 AAAABHCEG
I 6 AAAABHCEGG
F 5 AAAABHCEGGH

而不是我的预期:

A 3
B 4 A
C 2 A
E 5 A
G 3 A
J 8 BH
H 7 CEG
I 6 G
F 5 H

我在滥用sregex_token_iterator吗?

4

1 回答 1

3

这与正则表达式无关,与istream_iterator引擎盖下的一切有关:它只有一个T元素,当您增加它时它会读入:

istream_iterator& operator++();
3要求in_stream != 0
4效果*in_stream >> value
5回报*this

您的流运算符只是附加到rhs.precedentTask,但一开始不一定是空的。先把它清除掉。这也不是istream_iterator问题,您operator>>也必须能够在这种情况下工作:

Tache foo;
while (std::cin >> foo) {
    // ...
}

如果您所做的只是附加,那么第一个之后的每个后续Tache都将是错误的。你完全负责初始化对象的所有成员,你不应该对它们以前的值做任何假设。


我建议transform()只替换一个循环:

sregex_token_iterator it(cbegin(precedentTasks), cend(precedentTasks), re, 1), end;
for (; it != end; ++it) {
    rhs.precedentTask.push_back(it->front());
}

或将其包装在一个范围内:

for (std::string match : sregex_matches(precedentTasks, re, 1)) {
    rhs.precedentTask.push_back(match.front());
}
于 2016-06-06T19:47:56.003 回答