-6

I copied this code online. it is about sorting big numbers:

int n;
cin >> n;
vector<string> a(n);
for (int i = 0; i < n; i++) {
    cin >> a[i];
}
std::sort(a.begin(), a.end(), 
    [](const string &left, const string &right)
{
    if (left.size() != right.size()) 
    {
        return left.size() < right.size();
    } 
    else 
    {
        return left < right;
    }
});
for (const string &s : a) {
    cout << s << '\n';
}

Can somebody explain these lines by words:

[](const string &left, const string &right)

and

for (const string &s : a)

I have never encountered the library as well as a for loop like the code used. Thanks!

Mike Tran
  • 1
  • 2
  • [first](https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11/7627218#7627218), [second](https://stackoverflow.com/questions/15927033/what-is-the-correct-way-of-using-c11s-range-based-for) – Raymond Chen Sep 28 '17 at 05:31

1 Answers1

0

Read more about C++11 at least (or C++14 or C++17), e.g. some good C++ programming book (any standard older than C++11 is obsolete, and C++11 has evolved a lot since its predecessors, so you should almost consider C++11 as a new programming language). Look also some C++ reference site.

[](const string &left, const string &right) starts a lambda expression, that is an anonymous function implemented as a closure.

Then you have a range-for loop: for (const string &s : a) which could even be for (const auto& s: a) or in your case for (auto s: a) because the auto specifier brings a limited form of type inference.

Read also SICP to improve your views on programming (it is not about C++, but an excellent and freely downloadable introduction to programming).

Basile Starynkevitch
  • 1
  • 16
  • 251
  • 479