Sign in to follow this  
Replicon

Specifying behaviour of std::set::find()

Recommended Posts

Suppose I have something like this:
set<CWidget *> widgets;

// ... code to pupulate this thing....

CWidget *widget = new CWidget([...something]);

set<CWidget *>::iterator result = widgets.find(widget);

if(result != widgets.end()) {
    // rejoice, etc.
}

Ah, but since it's a set of POINTERS, it'll just compare the addresses to determine whether it's in the set... But what if in THIS case, I want the find() to operate on the dereferenced widgets to determine whether it exists. Is such a thing doable? I assume it is, and I probably need to 1. Define some standard operators to make CWidget compatible with all this, and 2. Define some comparator class (in the same way you use priority_queue). Since I'm out of town at the moment and don't have my trusty STL reference on me, I was wondering if you fine people could clue me in on it. (I could always force some kind of "CWidget::toUniqueInt()" and have a map<int, CWidget*>, but that == UGH!) thanks!

Share this post


Link to post
Share on other sites
Set has an optional second template parameter that is a compare functor that takes two parameters and returns true if the first is less than the second, and false otherwise. Just make one that operates on two Widget* objects, and you're gravy.

*edit: see here for an example involving c strings

CM

Share this post


Link to post
Share on other sites
You could also use std::find_if and supply a predicate, but I believe you'll go back to linear search time, which would be slower than std::set's find function.

I think you need to weigh the costs vs. your design goals/needs. If you supply set's compare object, the set will remain sorted based on that comparison. If this is desirable to you, by all means, take that approach. You can still always use std::find_if for custom searches.

Share this post


Link to post
Share on other sites
Quote:
Original post by Replicon
Sweet, it's just like priority_queue... I shoulda just tried it LOL. Thanks for the help.


Not quite, std::set must only contain unique items. A multiset would allow for multiple occurrences.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this