插入到unordered_map _模板时出现c ++错误

时间:2015-04-04 22:37:47

标签: c++11

我想在无序地图中插入一个值并收到以下错误:

removeduplicate.cpp:106:69: error: no matching function for call to ‘make_pair(int&, int)’

/usr/include/c++/4.8/bits/stl_pair.h:276:5: note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
     make_pair(_T1&& __x, _T2&& __y)

/usr/include/c++/4.8/bits/stl_pair.h:276:5: note:   template argument deduction/substitution failed:

removeduplicate.cpp:106:69: note:   cannot convert ‘temp->List<int>::node::data’ (type ‘int’) to type ‘int&&’
     if ( !Storage.insert(  std::make_pair< T , int >(temp->data , 1 ) .second )){

以下是代码:

template < class T >class List{
        private:
                struct node{
                        T data;
                        node *next;
                };


                node*    root;
                std::unordered_map< T , int>Storage;
        public:
                List():root( NULL){}
                ~List(){}
                node *getNode( T);
                bool insertNode();
                bool traverseList();
                int removeDuplicate();
};

以下是方法---

template< class T > int List<T>::removeDuplicate(){
        node *   temp;
        node*    prev;
        prev = NULL;
        temp = root;
        typename std::unordered_map<  T , int>::iterator it;
        int returnVal;
        returnVal = 0;


        while ( temp ){
                it =Storage.find( temp->data );
                if ( it != Storage.end() ){
                        prev->next = temp->next;
                        returnVal ++;
                }
                else{

以下一行投掷错误。

if ( !Storage.insert(  std::make_pair< T , int >(temp->data , 1 ) .second )){
                                 std::cerr<<"Could'nt able to inser in std::unordered_map< T , int>]n"<<std::endl;
                                 returnVal = -9999; 
                         }
                }        
                prev = temp;
                temp= temp->next;
        }

        return returnVal;
}

1 个答案:

答案 0 :(得分:0)

无法生成int&的地图,并且您的代码要求编译器执行此操作。尝试替换

std::unordered_map< T , int>Storage;

使用:

std::unordered_map< std::remove_reference<T>::type , int>Storage;

或更改getNode的声明:

node* getNode(const T&);