I'm kinda sorta new to C++ and I made a simple function that would retrieve certain word(s) from a string.
Usage:
WFS("Hello world 123 lawl test",2) returns "world"
WFS("Hello world 123 lawl test",-3) returns "123 lawl test"
You get the picture. I'm looking for a way to improve the function's speed. Don't get me wrong it's pretty fast, but the faster the better :) Any ideas?
The function interface is a little weird. If I specify a positive value N, I get just the Nth word. If I specify a negative value N, I get the last N words. If that's the behavior you want, then I'd split it into two functions first off.
In either case, there is no need to maintain a std::vector<> of words. This will improve performance. I'd replace the std::istringstream with a simple state machine. It makes the
code a little more complex because istringstream deals with consecutive spaces, but it will
speed up your code.
I'd make use of std::string::reserve to ensure that the string isn't reallocated each time you add a word or character to it.