使用二元谓词加函数绑定器实现vector中的快速搜寻算法find_if

#include "stdafx.h"
#include 
#include 
#include 
#include 
using namespace std;

typedef struct _Node
{
 int iHid;
 std::string strName;
}Node;


struct compare_hid:binary_function<Node,int,bool>
{
 bool operator()(Node& a,int hid)const
 {
  if(a.iHid == hid)
   return true;
  else 
   return false;
 }
};
struct compare_desc:binary_function<Node,string,bool>
{
 bool operator()(Node& a,string desc)const
 {
  if(a.strName == desc)
   return true;
  else 
   return false;
 }
};

typedef vector<Node>::iterator  Iter_Node;

int _tmain(int argc, _TCHAR* argv[])
{
 vector<Node> m_vecNodes;
 for (int i = 1; i < 10; i ++)
 {
  Node stNode = {0};
  stNode.iHid = i;
  ostringstream stream;
  stream<<i;
  stNode.strName = stream.str();
  m_vecNodes.push_back(stNode);
 }
 //查找,搜寻算法
 Iter_Node m_stNode = std::find_if(m_vecNodes.begin(),m_vecNodes.end(),bind2nd(compare_hid(),3));
 if (m_stNode != m_vecNodes.end())
 {
  int hid = (*m_stNode).iHid;
 }

 Iter_Node m_stNode2 = std::find_if(m_vecNodes.begin(),m_vecNodes.end(),bind2nd(compare_desc(),"7"));
 if (m_stNode2 != m_vecNodes.end())
 {
  int hid = (*m_stNode).iHid;
 }
 return 0;
}

 

你可能感兴趣的:(C++,c++,二元谓词,函数绑定器,STL模板,find_if)