I have function to check if a string contains only alphanumeric and underscore character...
inline bool IsValidChar(char x)
{
return (isalnum(x) || (x == '_'));
}
My find_if code is:
if(find_if(str.begin(), str.end(), IsValidChar) != str.end())
{
...
}
I just want to remove the IsValidChar function and directly put it's contents in the find_if line of code..
You're basically looking for C++0x lambda expressions:
if (find_if(str.begin(), str.end(),
[](char x) { return (isalnum(x) || x == '_'); })
!= str.end()) {
// Do something.
}
Frédéric Hamidi gave you a good example of how to use a lambda expression to do what you literally asked. However, the title of the question is "How To Optimize This find_if Code" (emphasis mine). The performance difference between the anonymous function and the named function is going to be negligible (hopefully zero!). Ideally either version can be fully inlined (assuming find_if
is inline) and even the slight differences between a lambda expression and a named function are irrelevant.
If (and that's a big if) you have profiled your code and find that this expression is the root of a performance bottleneck, then you would want to explore another algorithm for getting the same result. Since this is such a simple test (and unlikely to simplify further) you'd need to look at how you could make this test less frequently at a higher level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With