sort(arr.begin(), arr.end(), [arr](int& a, int& b) {}); // #1 - TLE
sort(arr.begin(), arr.end(), [](int& a, int& b) {}); // #2 - not TLE
What is the difference between []
and [arr]
, and why does TLE #1
occur?
Assuming TLE
is time limit exceeded for some online coding/competition site, [arr]
will capture the collection as a copy so that it's accessible to the lambda (a comparator for the sorting logic).
For a big enough collection (or a small enough timeout), this could cause an issue.
You really don't need to capture the array since you shouldn't be doing anything with it. The contract between std::sort
and the comparator is that you just indicate which of the two items is to be considered the larger, in a consistent manner.
I'm hoping that's not your complete code since you're meant to actually compare a
and b
somehow in the comparator function, and return the result of that comparison.
For example, a sorting the first few digits of π
, largest to smallest, 9 5 4 3 1 1
:
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector, std::sort, std::cout;
int main() {
vector<int> vec { 3, 1, 4, 1, 5, 9 };
sort(vec.begin(), vec.end(), [](int a, int b) {
return b < a;
});
for (const auto &x: vec)
cout << x << ' ';
cout << '\n';
}
Note that we could have used std::greater<int>()
rather than a lambda, but that wouldn't really show what you have to do in the lambda:-)
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.