3

I'm a novice with C++ and am wondering why std::sort() directly changes the array. I would naturally think that the sort() function should be like this:

anyVector = sort(anyVector.begin(), anyVector.end());

My question is: how std::sort() understands that it must change the order of the array content if you don't mention the array itself to be re-assigned?

I know that it could appear as a trivial question, but I didn't find any explanation (maybe because it's obvious for many).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
SYS64738
  • 37
  • 3
  • [`std::sort`](https://en.cppreference.com/w/cpp/algorithm/sort) does a sort *in place*. – Eljay Jun 09 '21 at 16:11
  • `std::sort()` sorts a range, provided by pair of iterators - the first for begin of the sequence, the second - one behind the last. Passing whole `vector` is just a variant of use. – Slava Jun 09 '21 at 16:12
  • I just needed the "in place" keyword thank you, now I read what means "pass by reference", I refreshed my old C notions with pointers, now it's clear the reason why sort use the reference and modify directly the value. Thank you very much @Eljay! – SYS64738 Jun 09 '21 at 17:10
  • You're welcome. :-) "*I would naturally think...*" I also naturally think that way, as there are less surprises (referential transparency, immutability... which are more in the *functional programming* camp). With *in place* mutability comes smaller memory footprint, which can be critical in many rather common situations, and provides some guarantees. I just wish the name was `std::sort_in_place`. Alas, that ship has sailed. – Eljay Jun 09 '21 at 17:38

1 Answers1

8

Algorithms like std::sort don't know about the container. You pass iterators and the algorithm works on iterators. Hence std::sort has no way to return a vector.

The more profane reason is that you always have to choose between doing something in-place or creating a copy. When the algorithms does its job in-place, you are still free to make a copy:

std::vector<int> my_sort(const std::vector<int>& v) {
      auto result = v; // passing v by value and returning it defeats NRVO
      std::sort(result.begin(), result.end());
      return result;
}

But the other way around is not possible. If the algorithm would make a copy, you cannot easily turn it into something that does not make a copy.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185