1

So I have currently a map which contains an unsigned long long as the key and an MyStruct object as it's value.

Currently in order to check if an incoming MyStruct object matches any of the objects in the map, I do a find on the unsigned long long variable (say a sequence number).

Thing is, I now have to do an extra check for the source and destination address as well as the sequence number in the map.

What's the best way to store the source, destination address and sequence number as a key in a map and be able to retrieve the value (the MyStruct object)?

Scis
  • 2,934
  • 3
  • 23
  • 37
  • 5
    Please post your current code so we can see what you're talking about in concrete terms. – John Kugelman Aug 25 '14 at 03:46
  • 1
    Possible duplicate of [Determine if map contains a value for a key?](http://stackoverflow.com/questions/3136520/determine-if-map-contains-a-value-for-a-key). The question uses an `int` rather than a `long long`, but the same should apply. And this might be relevant: [find() using overloaded operator==](https://stackoverflow.com/questions/19187766/find-using-overloaded-operator). – jww Aug 25 '14 at 03:50
  • @jww I think that the OP got the title wrong as what he asks in the last sentence is slightly different... – Scis Aug 25 '14 at 05:29

1 Answers1

1

As to the actual question:

What's the best way to store the source, destination address and sequence number as a key in a map and be able to retrieve the value (the MyStruct object)?

You can create a new struct that will contain the above mentioned fields. Something along the lines of.

Just remember that map relies on std::less<KeyType>, which defaults to the operator< so if you use a custom struct you should provide one either by implementing operator< or by providing a functional object (source):

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;

Or if creating it bothers you, use a tuple as key e.g (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;
}
Community
  • 1
  • 1
Scis
  • 2,934
  • 3
  • 23
  • 37