【问题标题】:Implementing of container with map inside实现带有地图的容器
【发布时间】:2014-07-28 18:48:41
【问题描述】:

我想实现里面有map的容器,实现插入key/value和key取值的操作。 模板使用经验不多,找不到错误。

  1. 第 1 行:错误 C2663:std::_Tree<_traits>::find:错误 C2663::2 重载不合法;
  2. 第 2 行:错误 c2664:std::pair<_ty1> std::_Tree<_traits>::insert(std::pair &&): param 1 from "std::pair<_ty1>" в "std::pair<_ty1> &&";

所以我有接口:

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

【问题讨论】:

  • map::find 需要key_type(在您的情况下为ElemType)。你传递给它一个IndexType。你的意思是写typedef std::map&lt;IndexType, ElemType&gt; CMap;

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


【解决方案1】:

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

【讨论】:

  • 或者干脆使用auto :)
  • 嗯,反正错误 C2663: : 2 重载不合法;
  • 对不起,但自动不决定我的麻烦,无论如何都会出错(
  • @user3780799 你有很多错误。这里是a fixed version of your code。主要问题是您的地图类型的键和元素类型错误。
猜你喜欢
  • 2013-03-21
  • 1970-01-01
  • 2023-04-07
  • 2014-09-13
  • 1970-01-01
  • 2019-07-03
  • 2020-03-09
  • 2022-08-10
  • 2019-02-01
相关资源
最近更新 更多