如何在 std::set 中为 FIND 和 ORDER 定义不同的条件
How to define different criteria for FIND and ORDER in std::set
#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 <<"已找到";
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何在 std::set 中为 FIND 和 ORDER 定义不同的条件