c++ - 使用 C++ 设置容器时出错

标签 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 的比较功能。 如果是这种情况,请解释。 我在使用 set container 时遇到问题,请帮忙谢谢,圣诞快乐!

最佳答案

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

关于c++ - 使用 C++ 设置容器时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8625606/

相关文章:

c++ - QScrollArea 与动态调整 subWidgets

C++ 在不激活构造函数的情况下分配内存

c++ - 如何正确显示文本文件中的最大数字?

c++ - 射线平面求交方向 vector

c++ - 如何编写新的 Windows Shell?

c++ - OS X 程序集中的 Zerofill 大小溢出

c++ - 有没有办法在不重载 << 运算符的情况下打印出 std::list 的内容?

android - 使用 NDK 在 C/C++ 中将 YUV 解码为 RGB

c++ - 在 C++ 中重载模板类的 [] 运算符,get 和 set

c++ - 手动签署 PE 文件