带有自定义比较器函数的C++中sort()的时间和空间复杂度是多少

What is the Time and space complexity of sort() in C++ with custom comparator function?

本文关键字:时间 空间复杂度 多少 自定义 比较器 函数 C++ sort      更新时间:2024-05-09

考虑以下代码-

bool cmp(pair<string,int> &a, pair<string,int> &b) {
return ((a.second > b.second) || (a.second==b.second && a.first<b.first));
}
vector<pair<string,int>> v;
sort(v.begin(),v.end(),cmp);

对于这种情况,我的复杂性是什么?会是O(nlogn)吗?

std::sort具有时间复杂性:O(NlogN(自定义比较
但在您的情况下,比较器函数cmp也执行字符串比较

(a.second==b.second&&a.first<b.first(

std::basic_string operator<的时间复杂度与字符串的大小呈线性关系。

因此,最坏情况下的复杂性是O(K*NlogN(字符比较,其中K是字符串的长度。