principlecppMinor
Set with custom compare
Viewed 0 times
withcustomcompareset
Problem
In my project I use
(tried
The important code is:
Naturally I want to avoid undefined behaviour. As far as I can see my Compare fulfills the requirements of strick weak ordering (irreflexive, transitive, asymetric)
Can you confirm that this code is well-defined, or am I missing something? Thanks for your time!
std::set with custom Compare function for maintaining an event queue. It fulfills following criteria:- event duplication is not allowed
- should maintain the insertion order
(tried
std::vector first, but that performed poorly because of complicated duplicate removal)The important code is:
template
class EventQueue {
public:
EventQueue() : set_(std::set()) {}
void Insert(T elem) {
set_.insert(DataWrap(elem, set_.size()));
}
// ....
private:
struct DataWrap {
T data;
unsigned int order;
DataWrap(T d, unsigned int o) : data(d), order(o) {}
bool operator set_;
};Naturally I want to avoid undefined behaviour. As far as I can see my Compare fulfills the requirements of strick weak ordering (irreflexive, transitive, asymetric)
Can you confirm that this code is well-defined, or am I missing something? Thanks for your time!
Solution
As a side note, you pass the element by copy not by const reference. This might also have some real preformance effects. SO rather do
Also you could use emplace_back to enable inplace construction of the elements in the vector. On the other hand std::find only takes const T& so I would guess, that move semantics do not really buy you anything here.
void Insert(const T&)Also you could use emplace_back to enable inplace construction of the elements in the vector. On the other hand std::find only takes const T& so I would guess, that move semantics do not really buy you anything here.
Code Snippets
void Insert(const T&)Context
StackExchange Code Review Q#159428, answer score: 2
Revisions (0)
No revisions yet.