如何使用带有std :: set的分配器?

Jon*_*nor 0 c++ set allocator c++14 c++17

我试图使用自己的分配器来测量C++中的内存使用情况std::set.不幸的是,我在链接时遇到错误.为了简化问题,我有以下程序:

#include<set>
#include<vector>
#include<memory>
//using Container = std::vector<int, std::allocator<int>>;
using Container = std::set<int, std::allocator<int>>;

int main() {
  Container container;
  container.push_back(4711);
  container.insert(4711);  
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果可以在wandbox https://wandbox.org/permlink/R5WcgSvSWiqstYxL#wandbox-resultwindow-code-body-1中找到

我试过gcc 6.3.0,gcc 7.1.0,clang 4.0.0和clang 6.0.0HEAD.在所有情况下,我使用a时都会出错std::set,但是当我使用a时却没有std::vector.

如何声明我的设置使用分配器?

我想使用C++ 17,但C++ 14中的答案也很好.

Rak*_*111 5

您应该std::set更仔细地查看模板参数:

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;
Run Code Online (Sandbox Code Playgroud)

当你写:std::set<int, std::allocator<int>>你说你想使用分配器来比较密钥.这没有任何意义,因为分配器不像比较器那样可调用,编译器会抱怨.

您需要显式提供Compare参数:

using Container = std::set<int, std::less<int>, std::allocator<int>>;
Run Code Online (Sandbox Code Playgroud)