2016-07-10 28 views
1

我是Javaer多年,是C++中的新手。最近我需要在C++項目上工作,但在使用C++時遇到一些令人不快的問題,其中一個是std:map地圖插入中的參數不匹配錯誤

我正試圖在地圖函數中插入一個鍵值對。

map[key]=valuemap.emplace(key,value)工作正常,但map.insert給我[編譯錯誤](error),我完全失去了。有人可以幫忙嗎?

class mystructure{ 
private: 
    int value; 
public: 
    mystructure(int v){ 
     value=v; 
    } 
    void print(){ 
     std::cout<<value<<std::endl; 
    } 
    std::string get_Value(){ 
     return std::to_string(value); 
    } 
}; 

int main(void) { 

    std::map<std::string, mystructure> mymap; 
    std::vector<mystructure> v = std::vector<mystructure>(); 
    v.push_back(*(new mystructure(17))); 
    v.push_back(*(new mystructure(12))); 
    v.push_back(*(new mystructure(23))); 
    for (int i=0;i<v.size();i++) { 
     mystructure temp=v.at(i); 
     mymap.insert(temp.get_Value(),temp);//compilation error 
    } 
    return 0; 
} 
+0

'*(新MYSTRUCTURE(17)))'C++中ñ Java。你在這裏創建一個內存泄漏。 Java中的'new'與C++中的'new'不同。使用值類型,而不是指針。 'v.push_back(mystructure(17));' – PaulMcKenzie

+0

@PaulMcKenzie你是對的,謝謝。 –

回答

3

由於std::map::insert接受std::map::value_type(即std::pair<const Key, T>)作爲它的參數。

你可以使用:

mymap.insert(std::pair<const std::string, mystructure>(temp.get_Value(), temp)); 

mymap.insert(std::make_pair(temp.get_Value(), temp)); 

mymap.insert({temp.get_Value(), temp}); 

LIVE

+0

它仍報告不匹配錯誤。 –

+0

@ShuhaoZhangtony什麼是錯誤信息?我嘗試過[這裏](http://rextester.com/JOELS2596)。 – songyuanyao

+0

我想我可能在CLion中發現了一個bug:在我按照你的建議之後,它仍然強調錯誤,但它編譯... –

相關問題