使用c++ set容器出错

error using c++ set container

本文关键字:出错 set c++ 使用      更新时间:2023-10-16

大家好,我是一个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创建比较函数。如果是这样的话,请解释一下。我在使用set container时遇到了麻烦,请帮忙,谢谢,圣诞快乐!

比较器是类型的部分。你必须处处说set<pairT, classcomp>。最好使用typedef

除了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>时,默认情况下将使用此操作符,因此您不必提供自己的操作符。