2011-12-24 56 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

相关问题