使用c++ set容器出错
error using c++ set container
大家好,我是一个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>
时,默认情况下将使用此操作符,因此您不必提供自己的操作符。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 使用运算符调用 void 函数时出错<set>
- openCL 和"Failed to set kernel argument"失败在哪里出错?
- 使用std::set实现稀疏三维网格时出错
- 运行提升 bcp 工具时出错:"The Boost path appears to have been incorrectly set"
- 插入 Set C++ 时出错
- 在 std::set 中查找对象时出错
- 使用c++ set容器出错