2011-12-24 54 views
1

大家好,我是C++的新手。 編譯這個程序後,我收到一個錯誤消息說。使用C++設置容器時出錯

assign3_3.cpp:120:9: error: could not convert 'sPair' from 'std::set<pairT, clas 
scomp>' to 'std::set<pairT>' 

這是我的代碼。

#include <set> 
#include <string> 
#include <iostream> 
using namespace std; 


struct pairT 
{ 
    string first, second; 
}; 

struct classcomp 
{ 
bool operator() (const pairT &lhs, const pairT &rhs) const 
{ 
    if (lhs.first == rhs.first && lhs.second == rhs.second) 
    { 
     return 0; 
    } 
    else if (lhs.first < rhs.first) 
    { 
     return -1; 
    } 
    else if (lhs.first == rhs.first && lhs.second < rhs.second) 
    { 
     return -1; 
    } 
    else 
    { 
     return 1; 
    } 
    } 
}; 

set<pairT> CartesianProduct(set<string> & one, set<string> & two); 

int main() 
{ 

    string A = "ABC"; 
    string B = "XY"; 
    set<string> sA, sB; 
    sA.insert(&A[0]); 
    sA.insert(&A[1]); 
    sA.insert(&A[2]); 
    sA.insert(&B[0]); 
    sA.insert(&B[1]); 
    set<pairT> pT = CartesianProduct(sA, sB); 
    //for (set<pairT>::iterator it = pT.begin(); it != pT.end(); it++) 
    // cout << pT.find(it).first << pT.find(it).second << endl; 

    return 0; 
} 


set<pairT> CartesianProduct(set<string> &one, set<string> &two) 
{ 
    set<string>::iterator itA, itB; 
    pairT pT; 
    set<pairT, classcomp> sPair; 

for (itA = one.begin(); itA != one.end(); itA++) 
{ 
    //cout << *itA << endl; 
    for(itB = two.begin(); itB != two.end(); itB++) 
    { 
     pT.first = *itA; 
     pT.second = *itB; 
     sPair.insert(pT); 
    } 
} 
return sPair; 
} 

首先,我不瞭解對pairT做比較函數。 如果這是這種情況,請解釋。 我有麻煩使用集合容器,請幫助感謝和聖誕快樂!

+1

一個想法:使用'std :: set >'。這不需要*額外的代碼。你需要'#include ',''和''。 – 2011-12-24 16:22:16

回答

3

比較器是類型的一部分。你必須隨處說出set<pairT, classcomp>。最好使用typedef。

+0

更簡單,使用'operator <' – wilhelmtell 2011-12-24 16:51:10

+0

@wilhelmtell:那麼,在任何嚴重的情況下,我都不會做任何這樣的事情,並按我在我的評論中所說的那樣做:-) – 2011-12-24 16:51:54

+0

啊,是的,我也是這麼說的。 :) – wilhelmtell 2011-12-24 16:52:51

0

除了Kerrek SB所說的,你的比較函數是不正確的。

通過std::set<std::pair>所需的比較器需要遵循以下邏輯:

if (lhs.first < rhs.first) 
    return true; 
else if (lhs.first == rhs.first && lhs.second < rhs.second) 
    return true; 
else 
    return false; 

這可以更緊湊地表示爲:

return lhs.first < rhs.first || 
    !(rhs.first < lhs.first) && lhs.second < rhs.second; 

幸運的是,這是怎麼std::pair::operator<在標準庫被定義。當您創建std::set<std::pair>時,此運算符將被默認使用,因此您不必提供自己的。

+0

後者並不嚴格比前者更「緊湊」,因爲您不知道「operator <'和'operator =='的定義是否兼容。 (他們應該沒有理由)。後者應被認爲是唯一正確的通用版本。 – 2011-12-24 16:53:10

相關問題