【问题标题】:What's the best way to store several values as a key in a map将多个值作为键存储在地图中的最佳方法是什么
【发布时间】:2014-10-18 04:19:06
【问题描述】:

所以我目前有一个地图,其中包含一个 unsigned long long 作为键和一个 MyStruct 对象作为它的值。

目前为了检查传入的MyStruct 对象是否与地图中的任何对象匹配,我在unsigned long long 变量(比如序列号)上进行查找。

问题是,我现在必须对源地址和目标地址以及地图中的序列号进行额外检查。

将源地址、目标地址和序列号作为键存储在映射中并能够检索值(MyStruct 对象)的最佳方式是什么?

【问题讨论】:

标签: c++ map


【解决方案1】:

关于实际问题:

存储源地址、目标地址和 序列号作为映射中的键并能够检索值 (MyStruct 对象)?

您可以创建一个包含上述字段的新struct。类似的东西。

请记住map 依赖于std::less<KeyType>,它默认为operator<,因此如果您使用自定义struct,您应该通过实现operator< 或通过提供功能对象(@987654322 @):

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 作为键,例如 (demo):

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2011-02-27
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多