替换' find_if '函数

Substituting `find_if` function

本文关键字:函数 if find 替换      更新时间:2023-10-16

我使用STL find_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;
    }
  }
}

不幸的是,我后来发现将运行这些代码的机器配备了libstdc++库版本4.1.1-21,显然缺少find_if。不用说,我不能升级这个库,也不能请别人来做。

编译时,我得到的错误是:

simulator.cc: In member function ‘void sim::Simulator::CommunicateEvent(sim::pEvent)’:
simulator.cc:168: error: no matching function for call to ‘find_if(std::_List_iterator<boost::shared_ptr<sim::Event> >&, std::_List_iterator<boost::shared_ptr<sim::Event> >, sim::Simulator::<anonymous struct>&)’
simulator.cc: In static member function ‘static void sim::Simulator::InsertEvent(sim::pEvent)’:
simulator.cc:191: error: no matching function for call to ‘find_if(std::_List_iterator<boost::shared_ptr<sim::Event> >&, std::_List_iterator<boost::shared_ptr<sim::Event> >, sim::Simulator::<anonymous struct>&)’
make: *** [simulator.o] Error 1

我该如何解决这个问题?

我想我可以像这里描述的那样定义一个find_if函数。然而,我有一些担忧:

  1. 性能怎么样?使用find_if的函数需要尽可能高效。
  2. 我如何做条件编译?我找不到告诉libstdc++安装版本的宏。

你对此有什么看法?蒂雅,Jir

<标题>引用

源文件:simulator.h和simulator.cc

<标题> 解决方案

Simulator类之外定义IsJustGreater并声明IsJustGreater_sSimulator的友元:

struct IsJustGreater_s : public std::unary_function<const pEvent, bool> {
  inline bool operator() (const pEvent e1) {return (e1->GetTime () > Simulator::m_eventTime);}
} IsJustGreater;

find_if中这样调用IsJustGreater:jt = find_if (it, m_eventList。end (), sim::IsJustGreater);

从错误中可以看出,您试图使用匿名类型作为参数。我不认为匿名类型可以作为模板参数。

从错误中,我相信你有这样的内容:

class Simulator {
    struct {
       bool operator(const pEvent& p) { ... } ;
    } IsJustGreater;
}

你想要的是给它一个名字,然后改变find_if来实例化这个类(见下文)

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() );

我看到你在std::list之前使用std::限定符,而不是std::find_if。尝试将std::放在前面,以便编译器可以在命名空间中找到它。