将多个值存储为映射中的键的最佳方法是什么
What's the best way to store several values as a key in a map
所以我目前有一个地图,其中包含一个unsigned long long
作为键和一个MyStruct
对象作为其值。
目前,为了检查传入的MyStruct
对象是否与映射中的任何对象匹配,我在unsigned long long
变量(例如序列号(上进行了查找。
问题是,我现在必须对源地址和目标地址以及地图中的序列号进行额外的检查。
将源、目标地址和序列号存储为映射中的键并能够检索值(MyStruct
对象(的最佳方法是什么?
至于实际问题:
存储源、目标地址和 序列号作为映射中的键,并能够检索值 (MyStruct 对象(?
您可以创建一个包含上述字段的新struct
。类似的东西。
请记住,map
依赖于 std::less<KeyType>
,默认为 operator<
,因此如果您使用自定义struct
,则应通过实现operator<
或提供功能对象(源(来提供一个:
struct MyKey{
Adress addr;
Destination dest;
SeqNum seq;
};
inline bool operator< (const MyKey& lhs, const MyKey& rhs){ /* something reasonable */ }
std::map<MyKey,MyStruct> myMap;
/* Or */
struct CmpMyType
{
bool operator()( MyKey const& lhs, MyKey const& rhs ) const
{
// ...
}
};
std::map<MyKey,MyStruct,CmpMyType> myMap;
或者,如果创建它困扰您,请使用tuple
作为关键,例如(演示(:
std::map<std::tuple<int,string,demo> ,int> a;
a.emplace(std::make_tuple(1,"a",demo {5}),1);
a.emplace(std::make_tuple(1,"a",demo {6}),2);
a.emplace(std::make_tuple(1,"b",demo {5}),3);
a.emplace(std::make_tuple(2,"a",demo {5}),4);
if(a.count(std::make_tuple(2,"a",demo {5}) )){
cout << a[std::make_tuple(2,"a",demo {5})] << endl;
}
if(a.count(std::make_tuple(2,"c",demo {5}))){
cout << a[std::make_tuple(2,"a",demo {5})] << endl;
} else {
cout << "Not there..." << endl;
}
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 检测win32服务创建和删除的最佳方法
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将线程中的数据存储到全局容器的最佳方法?
- 将一系列整数放入类的最佳方法是什么?
- 在派生类中使用基类的私有成员变量的最佳方法
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 将 pybind11 绑定标记为已弃用的最佳方法
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- C++中变量混叠的最佳方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?