简体   繁体   中英

How can I use an allocator with std::set?

I am trying to use my own allocator to measure memory usage in a C++ std::set . Unfortunately, I am getting errors at link time. In an effort to simplify the problem, I have the following program:

#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;
}

Results can be found in wandbox https://wandbox.org/permlink/R5WcgSvSWiqstYxL#wandbox-resultwindow-code-body-1

I have tried both gcc 6.3.0, gcc 7.1.0, clang 4.0.0 and clang 6.0.0HEAD. In all cases, I get errors when I use a std::set , but not when I use a std::vector .

How can I declare my set to use an allocator?

I want to use C++17, but answers in C++14 are fine too.

You should look at the template parameters of std::set more closely:

template<
    class Key,
    class Compare = std::less<Key>,
    class Allocator = std::allocator<Key>
> class set;

When you write: std::set<int, std::allocator<int>> you are saying that you want to use an allocator to compare the keys. That doesn't make any sense, and because an allocator is not callable like a comparator, the compiler complains.

You'll need to explicitly provide the Compare parameter:

using Container = std::set<int, std::less<int>, std::allocator<int>>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM