sa***************@gmail.com wrote:
Hi,
I am trying to convert a Java iterator loop to C++ STL? the loop looks
like this:
public static boolean func (List aList) {
int minX = 0
for (Iterator iter = aList.listIterator(1); iter.hasNext();) {
A a = (A) iter.next();
if (! closeEnough(minX, a.x) ) {
return true;
} else {
minX = a.x;
}
}
return false;
}
I am reading the "Effecitive STL" book, it said i should use STL
algorithm instead of writing my loop if possible. I was thinking of
using for_each(). But in this case, i need to update a local variable
'minX' and stop the iteration if certain condition is met. Should I
use for_each()? or I write my own iterator loop?
Thank you for any idea.
I think the algorithm you want is "find_if". You can then write your
own predicate. For example, you might have a class named "closeEnough"
to act as your predicate:
#include <functional>
class closeEnough : public std::unary_function<bool, int>
{
private :
int minX ;
public :
closeEnough() : minX(0) {}
bool operator()(int x)
{
// Your logic for the "closeEnough" function goes here.
// Note your ability to change minX as you like.
return true ;
}
} ;
Then your function above would reduce to something like the following
(forgive me if I got some of the logic backwards, but this is the
general idea):
#include <algorithm>
#include <list>
bool func(std::list<int> aList)
{
std::list<int>::iterator i ;
closeEnough cefunc ;
i = std::find_if(aList.begin(), aList.end(), cefunc) ;
return (i == aList.end()) ;
}