Choosing specific objects satisfying conditions

淺唱寂寞╮ 提交于 2019-12-24 09:24:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!