Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Optimize This find_if Code?

Tags:

c++

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..

like image 718
Kuroro Avatar asked Dec 21 '22 21:12

Kuroro


2 Answers

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.
} 
like image 136
Frédéric Hamidi Avatar answered Dec 24 '22 12:12

Frédéric Hamidi


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.

like image 25
Ben Jackson Avatar answered Dec 24 '22 11:12

Ben Jackson