选择满足条件的特定对象

发布于 2024-11-24 01:41:12 字数 708 浏览 2 评论 0原文

假设我有一些看起来非常大致像这样的对象:

class object
{
  public:
    // ctors etc.

    bool has_property_X() const { ... }
    std::size_t size() const { ... }

  private:
    // a little something here, but not really much
};

我将这些对象存储在一个向量内,并且该向量相当小(比如说,最多大约 1000 个元素)。然后,在性能关键算法中,我想选择既具有属性 X 又具有最小大小的对象(如果有多个此类对象,请选择其中任何一个)。我需要多次进行这种“选择”,并且属性 X 的持有和大小可能在选择之间有所不同,因此这里的对象在某种程度上是动态的。两个查询(属性、大小)都可以在恒定时间内完成。

我怎样才能最好地实现这一目标?性能在这里被认为很重要。我目前的想法:

1)使用带有合适谓词的 std::min_element 。这可能还需要 boost::filter_iterator 或类似的东西来迭代满足属性 X 的对象?

2)使用一些数据结构,例如优先级队列。我将存储指向对象的指针或引用包装器等等。至少对我来说,这感觉很慢,而且由于对象的动态特性,这甚至可能是不可行的。

对这些想法还有其他建议或评论吗?我应该继续尝试这些方案和配置文件中的任何一个或两个吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嗫嚅 2024-12-01 01:41:12

你最后的选择永远是一个好的选择。我们对代码如何运行的直觉常常是错误的。因此,在可能的情况下,分析对于关键代码总是有用的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文