Algorithm 替换“find_if”函数
我使用STLAlgorithm 替换“find_if”函数,algorithm,stl,c++,Algorithm,Stl,C++,我使用STLfind\u if编写了一个类方法。代码如下: void Simulator::CommunicateEvent (pEvent e) { pwEvent we (e); std::list<pEvent> l; for (uint32_t i = 0; i < m_simulatorObjects.size (); i++) { l = m_simulatorObjects[i]->ProcessEvent (we); //
find\u if
编写了一个类方法。代码如下:
void
Simulator::CommunicateEvent (pEvent e)
{
pwEvent we (e);
std::list<pEvent> l;
for (uint32_t i = 0; i < m_simulatorObjects.size (); i++)
{
l = m_simulatorObjects[i]->ProcessEvent (we);
// no action needed if list is empty
if (l.empty ())
continue;
// sorting needed if list comprises 2+ events
if (l.size () != 1)
l.sort (Event::Compare);
std::list<pEvent>::iterator it = m_eventList.begin ();
std::list<pEvent>::iterator jt;
for (std::list<pEvent>::iterator returnedElementIt = l.begin ();
returnedElementIt != l.end ();
returnedElementIt++)
{
// loop through the array until you find an element whose time is just
// greater than the time of the element we want to insert
Simulator::m_eventTime = (*returnedElementIt)->GetTime ();
jt = find_if (it,
m_eventList.end (),
IsJustGreater);
m_eventList.insert (jt, *returnedElementIt);
it = jt;
}
}
}
我怎样才能解决这个问题
我想我可以定义一个find_if
函数,如下所述。不过,我有一些顾虑:
Simulator
类之外定义了isjustmorear
,并声明isjustmorear
是Simulator
的朋友:
struct IsJustGreater_s : public std::unary_function<const pEvent, bool> {
inline bool operator() (const pEvent e1) {return (e1->GetTime () > Simulator::m_eventTime);}
} IsJustGreater;
struct isjustmorger\u s:public std::一元函数{
内联布尔运算符()(constpevente1){return(e1->GetTime()>Simulator::m_eventTime);}
}只是更大;
在find\u if
中调用IsJustGreater
,方法如下:
jt=find_if(it,m_eventList.end(),sim::isjustmore) 我看到您在
std::list
之前使用的是std:
限定符,而不是std::find_if
。尝试将std::
放在前面,以便编译器可以在命名空间中找到它。从错误中可以看出,您试图使用匿名类型作为参数。我不相信匿名类型可以作为模板参数
从错误中,我相信你有这样的想法:
class Simulator {
struct {
bool operator(const pEvent& p) { ... } ;
} IsJustGreater;
}
您想要的是给它一个名称,然后更改find_if来实例化该类(见下文)
IIrFundIf不在C++标准中,只有在C++ 0x草案中。@ Alxand Re:Cudio.FIDYIF如果< /C>是C++ 98,那么你可能会想到<代码> CopyOf>如果< /Cord>你可以发布一个不为你编译的示例程序吗?code>std::find_if应该在4.1.1中,因为它不完全是一个新模板。@Dave我认为你是对的。我刚刚读了
grep
'd/usr/include/c++/4.1/
,其中有find\u if
的参考。我刚刚用find\u if
编辑了这篇文章,其中包含了方法的定义和我得到的错误。我认为ADL应该从参数中选择名称空间。好消息。编译器抱怨“struct sim::Simulator::isjustmorer”仅在两个函数中的一个函数中使用了“find_if”——静态函数。现在我想知道如何使这样的结构成为静态的。你确定你还没有尝试使用类成员,而只是实例化一个新的IsJustGreater()?是的。问题是使用find_if
的函数是正常成员函数,而另一个函数声明为静态函数。我想问题就在于此。您是否将IsJustGreater声明为模拟器的成员变量?如果是这样,您可以将其声明为静态,以允许在静态函数中也使用它。如果它没有数据,您也可以在调用find_If时将实例创建为临时对象,而不将其作为成员存在。这是一个好主意。基本上,它是一个从std::一元函数
继承的结构,并重载了运算符()
。我会尽力去做的。
class Simulator {
struct {
bool operator(const pEvent& p) { ... } ;
} IsJustGreater;
}
class Simulator {
// class is now an inner named-class
struct IsJustGreater {
bool operator(const pEvent& p) { ... } ;
};
}
// This is how you use the class
jt = std::find_if(it, m_eventList.end(), IsJustGreater() );