我创建了一个简单的地图使用struct作为键但在运行时崩溃。 你能指出这个问题吗?非常感谢。
放置第3项时代码崩溃。
...
typedef struct pmjob
{
std::string jobId;
std::string jobGroup;
int reportingPeriod;
int compressionType;
bool operator == (const struct pmjob &other) const
{
return ((jobGroup.compare(other.jobGroup) == 0) && (reportingPeriod == other.reportingPeriod));
}
bool operator < (const struct pmjob &other) const
{
if (reportingPeriod < other.reportingPeriod)
{
if(jobGroup.compare(other.jobGroup) == 0)
return false;
}
return true;
//return ((reportingPeriod < other.reportingPeriod) || (jobGroup.compare(other.jobGroup)));
}
}PMJob;
typedef std::map<PMJob, int> PMJobMap;
PMJobMap List;
typedef std::pair<PMJob, int> PMJobPair;
答案 0 :(得分:0)
您的比较器无效。
bool operator < (const struct pmjob &other) const
它没有提供严格的弱排序。
有效比较器的示例:
bool operator < (const struct pmjob &other) const
{
// first compare most important member
if (reportingPeriod < other.reportingPeriod) {
return false;
}
if (other.reportingPeriod < reportingPeriod) {
return true;
}
// less important member
if (compressionType < other.compressionType) {
return false;
}
if (other.compressionType < compressionType) {
return true;
}
if (jobId < other.jobId) {
return false;
}
if (other.jobId < jobId) {
return true;
}
if (jobGroup < other.jobGroup) {
return false;
}
if (other.jobGroup < jobGroup) {
return true;
}
return false;
}
或使用std::tie
:
bool operator < (const struct pmjob &other) const
{
return std::tie(jobId, jobGroup, reportingPeriod, compressionType) <
std::tie(other.jobId, other.jobGroup, other.reportingPeriod, other.compressionType);
}