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

How to define different criteria for FIND and ORDER in std::set

本文关键字:ORDER 定义 条件 FIND std set 中为      更新时间:2023-10-16
#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 << "Foundn";
   else
     cout << "Not Foundn";
   if (clients.find(Client{"a0002"}) != clients.end()) // Not Found
     cout << "Foundn";
   else
     cout << "Not Foundn";     
   return 0;
}

set::find的输出结果与此文档匹配。set::find基于容器的比较对象,而比较对象又基于salary而不是client_id

问题>在这种情况下,我需要根据salary Clients进行排序,但是在搜索时,我想根据client_id进行搜索。有没有办法解决这个问题?我想使用 STL 函数而不是自己编写循环。

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

if ( find( clients.begin(), clients.end(

), Client{"a0001", 10} ) ) != clients.end())//Found cout <<"已找到";