Reputation: 33
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)?
Upvotes: 1
Views: 192
Reputation: 2984
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;
}
Upvotes: 1