I might go with an intermediate function. The code below illustrates it.
#include <iostream>
#include <set>
class Foo { // Your T
public:
int A;
int B;
Foo(int a, int b) : A(a), B(b) { }
};
template <typename T, typename Comparison>
void addToSet(std::set<T, Comparison>& s, Foo item)
{
for (auto i : s) {
if (i.B == item.B) {
// Do whatever you need here, currently item is not added.
return;
}
}
s.insert(item);
}
int main()
{
auto comp = [](Foo a, Foo b) { return a.A < b.A; };
std::set<Foo, decltype(comp)> sortedSet(comp);
auto quickAdd = [&sortedSet](Foo item) mutable { addToSet(sortedSet, item); };
quickAdd(Foo(1, 2));
quickAdd(Foo(5, 2)); // Shouldn't be seen
quickAdd(Foo(5, 5));
for (auto i : sortedSet)
std::cout << "A: " << i.A << ", B: " << i.B << '\n';
}
This outputs
A: 1, B: 2
A: 5, B: 5
Which should fit your criteria.
Some notes, I hardcoded the Foo type into the addToSet function because of the specific requirement about not adding items with matching B keys. The quickAdd
lambda in main is just so I don't have to always type sortedSet
as the first parameter. You can naturally modify the comp
function to get whatever behavior you want like sorting matching A keys by the B key, or A keys from high to low.