Beginner algorithm problem

New to STL algorithms and lambda functions. I have this problem where your have a vector of strings that you are supposed to filter into flags and parameters.

Example:
--print // flag = "--print"
--remove=the // flag = "--remove", parameter = "the"

If there is no '=' the whole string is a flag. If ther is a '=' substring to the left is the flag and substring to the right is parameter. You can't use loops.

The solution I came up with is this. I was wondering if there was a better way of solving this or if my code can be improved / any genreal tips.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for_each( arguments.begin(), arguments.end(),
              [](string & arg )
              {
                  auto it{find(arg.begin(), arg.end(), '=')};
                  if(it == arg.end())
                  {
                      //execute_flag(arg);
                  }
                  else
                  {
                      string flag, parameter;
                      copy( (it + 1), arg.end(), back_inserter(parameter) );
                      copy( arg.begin(), it, back_inserter(flag) );
                      //execute_flag(flag, parameter);
                  }                                                 
              });
Last edited on
your else has sufficient information to just use substring (substr(start, count) )
that whole else could just be execute_flag(arg.substr(...), arg.substr(...) );

also look at range based for loops. the lambda here seems not useful, given that idea. But its a good exercise to play with a lambda, if that was the goal.
Last edited on
You never change arg, so you should be able to make it const.
Topic archived. No new replies allowed.