1

I have a nested map containing a std::set<> STL, Is there any way to predefine the max size of set in c++?

Following is my DS:

std::map<Key, std::map<classObj, std::set<classObj> > > 

Can I define max size of std::set without defining the size of any of the map present above in the declaration of this DS?

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
BSalunke
  • 11,499
  • 8
  • 34
  • 68

2 Answers2

2

can I define max size of std::set

No.


To enforce a limit you should consider making your own data type for this purpose.

For example (just for illustration):

template<typename T, std::size_t N>
class CustomSet
{
    ...
};

Then use your special purpose type instead of std::set

std::map<Key, std::map<classObj, CustomSet<classObj, 10>>>

Edit

The std::set does accept a custom allocator. Whether you could provide your own allocator to achieve your goal is beyond me. However, personally I'd still make a custom data type.

James Adkison
  • 9,412
  • 2
  • 29
  • 43
0

The best solution is to wrap the std::set class and reimplement the methods that could add an 11th element: insert, emplace and emplace_hint.

The basic pattern is simple:

template< typename Key,
          typename Compare = std::less<Key>,
          typename Allocator = std::allocator<Key>>
class restrictedSet : private std::set<Key, Compare, Allocator>
{
    int maxElem;
public:
    restrictedSet(int maxElem) : maxElem (maxElem) { }
    using set::iterator;
    using set::begin;
    using set::end;
    //etc
    std::pair<iterator,bool> insert( value_type const& value )
    {
       if (size==maxElem) return std::make_pair(std::prev(end()), false);
       return set::insert(value);
    }
MSalters
  • 173,980
  • 10
  • 155
  • 350