簡體   English   中英

如何在C ++中實現自定義std集合?

[英]How implement a custom std collection in C++?

我想以std風格實現自定義集合數據結構。 在這個網站上已經有類似的問題 ,但是這個人明確地詢問不使用任何給定的std功能。

該實現應該與標准庫的其余部分兼容,並提供相同的接口,例如迭代器和類型特征。 我應該繼承哪個基類以及我的類必須實現什么?

為了提供有關實際數據結構的信息,它是一個哈希映射,其值連續存儲在內存中。 在內部,我將使用兩個std::vector和一個std::unordered_map

我應該從哪個基類繼承

沒有。 標准容器不是多態的; 他們的接口要求是根據必須支持的表達式非正式地指定的。 (將來,它們可能被正式指定為“概念”;但這還不是語言的一部分。)

我班需要實施什么?

請參閱C ++標准的[container.requirements]部分(目前是C ++ 11的第23.2節); 特別是指定各種容器類型必須支持的操作的表。 作為哈希映射,它應該支持“無序關聯容器”的要求。

從類似於此的界面開始:

template <
    typename Key,
    typename T,
    class Hash = hash<Key>,
    class Pred = equal_to<Key>,
    class AllocH = allocator< pair<const Key,T> >,  // unordered_map allocator
    class AllocV = allocator<T> > // vector allocator
class hash_map {
public:
  typedef std::pair<Key, T> value_type;

private:
  using first_index = std::vector<T>; // C++11 typedef substitute syntax
  using second_index = std::unordered_map<Key, T>;

public:          
  using first_index_iterator = typename first_index::iterator;
  using second_index_iterator = typename second_index::iterator;      
  //defaults
  using iterator = first_index_iterator;
  using const_iterator = first_index_const_iterator;

  iterator begin();
  const_iterator begin() const;

  iterator end();
  const_iterator end() const;

  bool empty() const;

  iterator find(const Key&);
  const_iterator find(const Key&) const;

  std::pair<iterator, bool> insert(const value_type&);
  void erase(iterator);  
  void clear();    
};

您不應該將集合添加到std命名空間,但是如果繼續,我強烈建議您在發布庫頭時使用命名空間版本控制:

// hash_map.hpp
namespace std 
{
  namespace ex_v1  // my std namespace extensions v1
  {
      template <...> class hash_map { ... }    
  }

  using namespace ex_v1;
}

進一步,考慮C ++ 11的新內聯版本控制功能:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM