12

Does anyone know of a library that allows you to do something like this?

std::transform(vecA.begin(), vecA.end(), 
               vecB.begin(), 
               vecOutput.begin(), 
               // run-time specified expression 
               magic_functor<float>("exp(a/(b+3))") 
);

Where magic_functor is the library-provided functor and a and b are iterated through vecA and vecB.

I could come up with something myself (and would have a lot of fun doing so), but it's probably better to avoid reinventing the wheel (also my boss would kill me). Have spent some time searching the web, but can't really find anything that fits the bill.

It needs to be flexible and fast, so a functor approach that only parses the string once (e.g. creates an execution stack internally on construction) would be ideal, but am open to other solutions.

smocking
  • 3,689
  • 18
  • 22
  • 2
    That actually seems like a fun thing to make now that you mention it. – chris Apr 11 '12 at 21:13
  • 2
    I'm afraid I can't suggest any libraries which would do something like that with the kind of binary-functor interface you'd need; however I'd imagine it'd be fairly simple to write lambda expressions which handle your `exp(a/(b+3))`. Possibly not the most sophisticated solution if you need to repeat it in multiple locations, but as far as readability goes it would seem OK to me. – Ben Cottrell Apr 11 '12 at 21:15
  • People waste way too much time finding some complicated solution for evaluating expressions. It is easy to write a parser/interpreter to do what you want. See my SO answer on how to write recursive descent parsers. This should take you an afternoon. https://stackoverflow.com/a/2336769/120163 – Ira Baxter Jan 21 '19 at 03:50

1 Answers1

4

Several options (need some work and won't work “out of the box”):

Petr
  • 750
  • 6
  • 8
Anonymous
  • 18,162
  • 2
  • 41
  • 64
  • Would be nice to do boolean and bitwise stuff and Mathpresso seems to be a bit lacking in flexibility, being float only. Writing my own with Boost Spirit, though a fun project, would be a lot of work and likely not that efficient. Think I might give MuParserSSE a try, since it's a good deal faster than MuParserX and I don't need the extra features of the latter. – smocking Apr 13 '12 at 17:54
  • I think Spirit way might turn out to be the most flexible one... It's a bit difficult to get started, but there are many examples - on the Spirit blog, the one I posted and in Spirit examples. – Anonymous Apr 13 '12 at 18:05
  • I certainly like that it's header-only. Maybe when I have some time to kill. – smocking Apr 13 '12 at 18:24