问题
Let's say I have objects which look very roughly like this:
class object
{
public:
// ctors etc.
bool has_property_X() const { ... }
std::size_t size() const { ... }
private:
// a little something here, but not really much
};
I'm storing these objects inside a vector and the vector is rather small (say, at most around 1000 elements). Then, inside a performance critical algorithm, I would like to choose the object that both has the property X and has the least size (in case there are multiple such objects, choose any of them). I need to do this "choosing" multiple times, and both the holding of the property X and the size may vary in between the choices, so that the objects are in a way dynamic here. Both queries (property, size) can be made in constant time.
How would I best achieve this? Performance is profiled to be important here. My ideas at the moment:
1) Use std::min_element with a suitable predicate. This would probably also need boost::filter_iterator or something similar to iterate over objects satisfying property X?
2) Use some data structure, such as a priority queue. I would store pointers or reference_wrappers to the objects and so forth. This atleast to me, feels slow and probably it's not even feasible because of the dynamic nature of the objects.
Any other suggestions or comments on these thoughts? Should I just go ahead and try any or both of these schemes and profile?
回答1:
Your last choice is always a good one. Our intuitions about how code will run are often wrong. So where possible profiling is always useful on critical code.
来源:https://stackoverflow.com/questions/6669733/choosing-specific-objects-satisfying-conditions