将多个值存储为映射中的键的最佳方法是什么

What's the best way to store several values as a key in a map

本文关键字:最佳 方法 是什么 映射 存储      更新时间:2023-10-16

所以我目前有一个地图,其中包含一个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;
}