c++ - 复制构造函数调用 boost::multi_index_container 中的自定义排序谓词

标签 c++ boost copy-constructor boost-multi-index

我正在使用 boost::multi_index_container 为一组对象提供多个 View 和排序顺序。最近,我想使用自定义排序谓词对容器进行排序,该谓词(实质上)预先计算所有对象的属性值,然后使用这些值对它们进行排序(示例代码见下文)。

容器被正确排序,但我注意到用这个谓词排序比用 operator() 简单地访问我的 internal 属性的谓词排序需要更长的时间对象。

进一步的调查表明,我的谓词的(隐式定义的)复制构造函数被调用得非常频繁。由于谓词的每个拷贝都包含完整属性映射的拷贝,因此这需要很长时间。

我已经通过向我的对象添加一个内部属性解决了这个问题,但我仍然不相信这是最好的做法。所以,我想知道:

  • 为什么经常调用复制构造函数?
  • 我是否正确定义了谓词?谓词不应该包含这么多内部数据吗?
  • 有什么比定义另一个内部对象属性更好的解决方案?

这是我的代码的相关部分。我没有详细描述 Object 类,因为它的属性不会导致问题。

class Predicate
{
public:
  Predicate()
  {
    // fill _attributes map with attribute values for all objects
  }

  bool operator()(const Object& a, const Object& b) const
  {
    std::map<Object, double>::const_iterator firstPos = _attributes.find( a );
    std::map<Object, double>::const_iterator secondPos = _attributes.find( b );

    // throw error if one of the objects could not be found

    return( firstPos->second < secondPos->second );
  }

private:
  std::map<Object, double> _attributes;
};

// Later, in order to sort the container
_container.sort( Predicate() );

最佳答案

一个解决方案是在谓词之外构造一次属性映射,并让谓词持有对该映射的 const 引用。另一种选择是将 std::refboost::ref 传递给排序函数的谓词。这将避免不必要地复制 Predicatestd::map 数据成员。

Predicate p; // builds map internally
_container.sort( boost::ref(p) );

关于c++ - 复制构造函数调用 boost::multi_index_container 中的自定义排序谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12383610/

相关文章:

c++ - 如何初始化 RSA::PrivateKey?

c++ - 如何根据用户输入创建函数?

c++ - 基于 Boost spirit 语法的字符串拆分

java - 复制构造函数不起作用

c++ - gcc/clang 在基本结构的后填充中布置派生结构的字段

c++ - 如何在我的软件中配置中文支持?

C++ 相互递归变体类型(再次)

c++ - Windows 进程和 WSL Linux 进程之间的共享内存

c++ - 生成有关使用复制构造函数和赋值的警告

c++ - 以 vector 为成员变量的对象复制构造函数