【问题标题】:Is there any way to predefine std::set size in c++?有没有办法在 C++ 中预定义 std::set 大小?
【发布时间】:2015-06-15 18:41:49
【问题描述】:

我有一个包含 std::set STL 的嵌套映射,有没有办法在 c++ 中预定义集合的最大大小?

以下是我的 DS:

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

我可以定义 std::set 的最大大小而不定义此 DS 声明中上述任何映射的大小吗?

【问题讨论】:

  • 为什么需要?这似乎是XY problem...
  • @JamesAdkison 我只想在集合中存储 10 个元素,但不超过这个,这是要求。
  • 然后编写代码来做到这一点。你不需要任何特别的东西。
  • @BSalunke 如果添加第 11 个元素会发生什么?

标签: c++ dictionary set nested-map


【解决方案1】:

我可以定义 std::set 的最大尺寸吗

没有。


要强制实施限制,您应该考虑为此目的创建自己的数据类型。

例如(仅用于说明):

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

然后使用您的特殊用途类型而不是std::set

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

编辑

std::set 接受自定义分配器。您是否可以提供自己的分配器来实现您的目标,这超出了我的范围。但是,我个人仍然会制作自定义数据类型。

【讨论】:

    【解决方案2】:

    最好的解决方案是包装 std::set 类并重新实现可以添加第 11 个元素的方法:insertemplaceemplace_hint

    基本模式很简单:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多