在Map中使用Node, c++

Using Node in Map, C++

本文关键字:Node c++ Map      更新时间:2023-10-16
class MtmMap {   
    public:    
    class Pair {     
         public:   
         Pair(const KeyType& key, const ValueType& value) :     
             first(key),       
             second(value) { }    
         const KeyType first;    
         ValueType second;    
     };     
    class node {    
        friend class MtmMap;    
        Pair data;    
        node* next;     
        public:    
        node();    
        node(const Pair& pair){
            data.Pair(pair.first , pair.second);
            next = NULL;
        }    
    };
    node* temp = new node(pair);
}

错误:

没有匹配函数调用'mtm::MtmMap<int,>::Pair::Pair()'
无效使用'mtm::MtmMap<int,>::Pair::Pair'
from void mtm::MtmMap::insert(const
)mtm::MtmMap<KeyType,>::Pair&) [with KeyType = int;ValueType = int;
CompareFunction = AbsCompare]'

通过为Pair定义一个带参数的构造函数,您删除了不带参数的隐式默认构造函数。当你在node中有Pair类型的成员时,它必须在节点的初始化列表中传递参数给它,你需要用以下方式替换你的节点构造函数:

    node(const Pair& pair) : data(pair.first, pair.second) {
        next = NULL;
    }

将正确调用data上的构造函数。Learn Cpp有一个关于初始化器列表如何工作的教程,你可能想要阅读。

首先映入我眼帘的是这一行:

node* temp = new node(pair);

看起来你试图在类定义中new一个类。这可能是问题的一部分。另外,这个区域看起来有点混乱:

node(const Pair& pair){
  data.Pair(pair.first , pair.second);
  next = NULL;
}

看起来你试图直接调用Pair构造函数。我不确定这对c++是否有效。实际上,只需像这样为Pair定义一个复制构造函数:

Pair( Pair const& other )
  : first( other.first )
  , second( other.second )
{}

然后,该块变成

node( Pair const& pair )
  : data( pair )
  , next( NULL )
{}

您也可以检查std::pair