0

There are a couple of ways to traverse and process a range of data, but when things get more complex, it becomes quite hard, too.

If each operation is independent, life is easy:

[1] modification

for(auto&& x : v)
    x += 1;

[2] access

for(const auto& x : v)
    sum += x;

If things get more complicated, ways to handle an element are dependent to the context (parsing for example). Then we have to maintain an automaton:

[1] explicit state

// I think this method is quite unintuitive though
auto state = kDefaultState;
for(const auto& x : v)
{
    if(state == kFirstState)
    {
        // deal with x...
        // transfer state
    }
    else if(state == kSecondState)
    {
        // deal with x...
        // transfer state
    }
    else
    {
        // ...
    }
}

[2] implicit state hidden in the code flow(create a reader class)

// this method require a lot more extra coding and redundant bound check
auto reader = CreateReader(...);
while(reader.Exhausted())
{
    if(reader.Try(...))
    {
        // ...
    }
}

while(reader.Exhausted())
{
    // ...
}

I'm wondering if there are some other better styles to deal with such kind of problems.

  • 2
    Take a look at [Chain of responsibility](https://sourcemaking.com/design_patterns/chain_of_responsibility) pattern. – Yuriy Ivaskevych Feb 28 '17 at 13:23
  • This is a pretty broad question. Even if isolating down the the case of how to represent and pump data into a finite state machine, it's still too broad. – paddy Feb 28 '17 at 13:29

0 Answers0