I have asked in another question about std::multiset, but now I see I need a decent understanding and cannot find any more complicated example in the internet.
Can you explain to me, maybe exemplarize, how std::multiset<A,B>
works and what function is here of A and of B, and also if any of those can be omitted? Can I put A or B to some variable?
I'd really appreciate some short example, or reference,
Multisets are part of the C++ STL (Standard Template Library). Multisets are the associative containers like Set that stores sorted values (the value is itself the key, of type T), but unlike Set which store only unique keys, multiset can have duplicate keys. By default it uses < operator to compare the keys.
std::multiset is an associative container that contains a sorted set of objects of type Key. Unlike set, multiple keys with equivalent values are allowed. Sorting is done using the key comparison function Compare.
The std::multiset
class template has a first template parameter specifying the type of objects to be stored in the set, and a second one specifying the type of a comparison functor. We can ignore the third template parameter for now.
The second, optional, parameter, B
, must implement strict weak ordering and is used to order the set/multiset. This ordering is required to ensure the logarithmic complexity of element look-up operations. Here is an example:
struct A
{
int x;
};
struct B
{
bool operator()(const A& lhs, const A& rhs) const {
return lhs.x < rhs.x;
}
};
This class B
has an operator()
, which means that it can be called, for example
B comp;
A a1, a2;
bool a1lessThana2 = comp(a1, a2);
This is needed for the set/multiset to place elements in the correct location, and figure out if two elements are the same. If there is an operator<
for your type, the second template parameter can be omitted.
bool operator<(constA& lhs, const A& rhs) { return lhs.x < rhs.x; }
This is an example of usage:
int main()
{
std::multiset<A, B> m;
A a1, a2;
a1.x = 23;
a2.x = 100;
m.insert(a1);
m.insert(a2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With