3

What is the difference between using sort(str.begin(), str.end()) and using sort(std::begin(str), std::end(str)) in C++?

Both of these functions gave the same result as the sorted string but is there any difference between the two, and what is the reason for having both?

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • `std::begin()` and `std::end()` were introduced in C++11. The `begin()` and `end()` members of all standard containers have existed since (at least) C++98. Functionally, for standard containers, `std::begin()` and `std::end()` call the corresponding member functions for the object passed to them (which, with a suitably optimising compiler doing inlining, means they are largely equivalent). There are also overloads of `std::begin()` and `std::end()` for raw arrays - which don't have member functions. – Peter Jan 03 '23 at 10:01

2 Answers2

12

Same thing, but if you write begin(str) it also works with things like arrays. If str was an array then str.begin() wouldn't work because an array isn't a class. Therefore some people like to make a habit of writing begin(str).

user253751
  • 57,427
  • 7
  • 48
  • 90
7

From the c++ reference of std::begin, for a non-array:

  1. Returns exactly c.begin(), which is typically an iterator to the beginning of the sequence represented by c. If C is a standard Container, this returns C::iterator when c is not const-qualified, and C::const_iterator otherwise.

Hence, using str.begin() or std::begin(str) for a std::string str is exactly the same.

francesco
  • 7,189
  • 7
  • 22
  • 49