Consider the following code-
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);
For this case, what would be my complexity? Will it be O(nlogn)
?
std::sort
has time complexity: O(NlogN) custom comparisons .
But in your case the comparator function cmp
also performs string comparison ,
(a.second==b.second && a.first<b.first)
std::basic_string operator<
has time complexity linear in the size of the strings.
Hence, worst case complexity is O(K*NlogN) char comparisons , where K is length of the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.