我有QString
项目名称,例如"放咖啡","启动咖啡机"或"将牛奶倒入咖啡"。我有这样的类来描述依赖(剥离不相关的东西):
class ImportWithDependency {
public:
// varargs je pro lenochy
ImportWithDependency(const QString& itemName, const QString& dependsOn = "", const QString& dependsOn2="", const QString& dependsOn3 = "")
: NAME(itemName)
, LOCALISED_NAME(getViewLocalisedName(viewName))
{
if (!dependsOn.isEmpty())
dependencies << dependsOn;
if (!dependsOn2.isEmpty())
dependencies << dependsOn2;
if (!dependsOn3.isEmpty())
dependencies << dependsOn3;
}
// cannot be const for sorting
QString NAME;
QStringList dependencies;
};
我想对QList<MyDependencyInfo>
的项目进行排序,以便项目前面没有依赖于它的项目。
我创建了以下比较器:
class ImportDependencyComparator
{
public:
bool operator()(const ImportWithDependency& a, const ImportWithDependency& b) const
{
// check if a depends on b
if (a.dependencies.contains(b.NAME))
return true;
else
return false;
}
};
我按照以下方式创建列表:
QList<ImportWithDependency> views;
views << ImportWithDependency("A");
// B depends on A
views << ImportWithDependency("B", "A");
// C depends on A
views << ImportWithDependency("C", "A");
// D depends on B
views << ImportWithDependency("D", "B");
我喜欢这样:
std::sort(views.begin(), views.end(), ImportDependencyComparator());
结果是:
D B C A
而不是:
A B C D
我收到的订单似乎是随机的,但每次都是相同的。怎么了?这甚至可以用于分类吗?