用里面的地图实现容器

时间:2014-07-28 18:48:42

标签: c++ c++11 stl stdmap

我想实现带有map的容器,并实现insert key / value的操作并按键获取值。 我在模板使用方面没有多少经验,也找不到错误。

Screenshot

  1. 第1行:错误C2663:std :: _ Tree< _Traits> :: find:错误C2663 :: 2重载没有合法性;
  2. 第2行:错误c2664:std :: pair< _Ty1,_Ty2> std :: _ Tree< _Traits> :: insert(std :: pair&&):来自“std :: pair< _Ty1,_Ty2>”的参数1 “std :: pair< _Ty1,_Ty2>&&”;
  3. 所以我有界面:

    IContainer.h
    
    class ElemNotFound {};
    template <class ElemType, class IndexType> 
    class IContainer
    {
    public:
        virtual ~IContainer() {};
        virtual const ElemType& GetElem( const IndexType& index ) const throw ( ElemNotFound ) = 0;
        virtual void PutElem( const IndexType& index, const ElemType& elem ) throw () = 0;
    };
    

    并且

    Container.h
    
    #include <map>
    #include "IContainer.h"
    
    template <class ElemType, class IndexType>
    class Container: public IContainer <ElemType, IndexType>
    {
    private:
        typedef  std::map<ElemType, IndexType> CMap;
        CMap myMap;
    
    public:
        inline const ElemType& GetElem( const IndexType& index ) const throw ( ElemNotFound ) {
    
            auto  it = myMap.find(index); // line 1
    
            if (toRet == end()) {
                throw ElemNotFound();
            }
    
            return toRet->second;
         }
    
         inline void PutElem( const IndexType& index, const ElemType& elem ) throw () {
             myMap.insert(make_pair(index, elem));  // line 2
         }
    };
    
    int main()
    {
        Container < string, int> c;
        c.PutElem(1, "as");
        c.PutElem(2, "G");
        c.GetElem(2);
    
        return 0;
    }
    

1 个答案:

答案 0 :(得分:3)

GetElem是一种const方法,因此您需要获得const_iterator,因为这是const overload of std::map::find返回的内容。您还需要使用typename,因为const_iterator是此上下文中的从属名称:

typename CMap::const_iterator it = myMap.find(index);

您可以使用auto自动获取此信息:

auto it = myMap.find(index);

请注意,您可以将该成员函数简化为

const ElemType& GetElem( const IndexType& index ) const
{
  return myMap.at(index);
}

如果可以返回std::out_of_range例外。另请注意,不推荐使用异常规范。

除此之外,toRet未声明,end()也未声明,myMap的类型具有错误的键和映射类型。您的代码here有一个固定版本。