2014-05-18 45 views
0

Implementing class for disjoint sets C++的std ::地圖與用戶定義的數據類型


struct Set 
{ 
    int parent,rank; 
    Set(int i):parent(i),rank(0){} 
    Set(const Set& s2):parent(s2.parent),rank(s2.rank){} 
}; 


struct Disjoint 
{ 
    std::map<int,Set> forest; 
    Disjoint(){} 
    void init_node(int i) 
    { 
     forest[i]=Set(i);//error here 
    } 
}; 

Now after compiling it I see,

/usr/include/c++/4.7/bits/stl_map.h:458:錯誤:沒有匹配的功能()::
DU_SET.cpp:13:5:備註:候選人是:
DU_SET.cpp: :候選人期望1個支持者個nt,0提供
DU_SET.cpp:12:5:注意:設置::集(INT)
DU_SET.cpp:12:5:注:候選預計1個參數,0提供*

I have also implemented the copy constructor for class Set but the same error comes back again. when I implement another constructor with no parameters it works fine but why*

+0

STL需要默認的構造函數.. – ikh

+0

那麼,重複?http://stackoverflow.com/questions/695645/why-does-the-c-map-type-argument-require-an-empty-constructor-when-使用 –

+0

說出'forest.insert(std :: make_pair(i,Set(i)))'。 –

回答

0

由於在聲明中

forest[i]=Set(i); 

forest[i]將嘗試創建一個使用默認構造Set對象,並放置在該位置。然後將使用Set(i)創建另一個,並將使用賦值運算符將其分配給第i個位置。因此你必須提供一個默認的構造函數。

要避免使用std::map::insert方法。

forest.insert({i, Set(i)}); 
0

使用std::map::emplacereference)直接在地圖構造的對象:

forest.emplace(i, i); 

注意:首先i將被用於構造密鑰,第二i將用於構造對象Set

+0

這不是'emplace'的作用。相反,它從參數構造一個'value_type'。 OP的不明智的隱含構造函數恰好使這項工作。 –

+0

我是怎麼說的?如果你願意的話,你也可以使用emplace(我,Set {i})。 – Danvil

+0

好吧,這聽起來很危險,就像你建議參數在關鍵構造函數參數和映射值構造函數參數之間以某種方式分離,但事實並非如此。相反,一切都傳遞給'pair'構造函數。 –

相關問題