如何在std :: set中为FIND和ORDER定义不同的标准

时间:2013-10-18 15:55:36

标签: c++ stl

#include <iostream>
#include <set>
#include <string>
using namespace std;

struct Client {
   string client_id;
   int    salary;   

   // allow client to sorted by salary
   bool operator<(const Client& rhs) const {
      return salary < rhs.salary;
   }

   // expect to search on client_id but this doesn't work
   bool operator==(const Client& rhs) const {
      return client_id == rhs.client_id;
   }
};    

int main()
{
   set<Client> clients;

   clients.emplace(Client{"a001", 10});
   clients.emplace(Client{"a002", 20});

   if (clients.find(Client{"a0001", 10}) != clients.end()) // Found
     cout << "Found\n";
   else
     cout << "Not Found\n";

   if (clients.find(Client{"a0002"}) != clients.end()) // Not Found
     cout << "Found\n";
   else
     cout << "Not Found\n";     
   return 0;
}

set::find的输出结果与this document匹配。 set::find基于容器的比较对象,而后者又基于salary而不是client_id

问题&GT;在这种情况下,我需要根据Clients订购salary,但在搜索时我想根据client_id进行搜索。有办法解决这个问题吗?我想使用STL函数而不是自己写一个循环。

1 个答案:

答案 0 :(得分:0)

您可以使用标准算法std :: find

if(find(clients.begin(),clients.end(),Client {“a0001”,10}))!= clients.end())//找到      cout&lt;&lt; “找到\ n” 个;