我重载了我的类' ()运算符以将其用作排序比较器函数.当使用std :: sort()时,它由于某种原因多次调用类的析构函数(显然取决于向量中的条目数量).我在~RANK()中描述了更多.
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
class RANK
{
struct COMBO
{
int x;
};
std::vector<COMBO *> data;
public:
RANK()
{
printf("RANK()\n");
}
~RANK()
{
printf("~RANK()\n");
/*
* Here is the problem.
* Since my vector consists of pointers to COMBO objects,
* I delete them upon RANK object's destruction. However,
* std::sort() calls RANK's destructor many times and
* throws some runtime error, unless commented out.
*/
//for (unsigned int i = 0, n = data.size(); i < n; i++)
// delete data[i];
}
void Add(int x)
{
COMBO *combo = new COMBO();
combo->x = x;
data.push_back(combo);
}
unsigned int Size()
{
return data.size();
}
void Sort()
{
std::sort(data.begin(), data.end(), *this);
}
int operator[](unsigned int pos)
{
return data[pos]->x;
}
bool operator()(COMBO *combo1, COMBO *combo2)
{
return combo1->x > combo2->x;
}
};
int main()
{
RANK rank;
rank.Add(1337);
rank.Add(9001);
rank.Sort();
for (unsigned int i = 0, n = rank.Size(); i < n; i++)
printf("%d ", rank[i]);
printf("\n");
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出(带注释析构函数):
RANK()
~RANK()
~RANK()
~RANK()
~RANK()
~RANK()
9001 1337
Run Code Online (Sandbox Code Playgroud)
std :: sort的比较函数按值传递.通过使用RANK对象作为比较器,您将副本传递给std::sort(作为最后一个值),并且它可以在内部多次复制它.
我建议从类RANK中分离掉COMBO的比较运算符