Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code an abuse of STL's find_if?

Tags:

c++

stl

Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:

find_if(serverNames.begin(), serverNames.end(), ContactServer());

Where ContactServer is a predicate function object.
On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (i.e. the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.

What do you say?

like image 825
On Freund Avatar asked Aug 26 '08 09:08

On Freund


1 Answers

I think I would go for it.

The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.

You might want to rename ContactServer to indicate that it is a predicate; CanContactServer? (But then people would complain about hidden side effects. Hmm...)

like image 199
Magnus Hoff Avatar answered Nov 08 '22 05:11

Magnus Hoff