我正在尝试使用我自己的分配器来测量 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;
}
结果可以在 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。在所有情况下,我在使用 std::set
时都会出错,但在使用 std::vector
时不会出错。
如何声明我的集合使用分配器?
我想使用 C++17,但 C++14 中的答案也很好。
最佳答案
你应该看看 std::set
的模板参数更紧密地:
template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;
当你写:std::set<int, std::allocator<int>>
你是说你想使用分配器来比较键。这没有任何意义,并且因为分配器不像比较器那样可调用,所以编译器会提示。
您需要明确提供 Compare
参数:
using Container = std::set<int, std::less<int>, std::allocator<int>>;
关于c++ - 如何将分配器与 std::set 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803409/