Reputation: 443
I want to sort a vector
using sort
algorithm in C++.
str
is the name of std::vector<int>
I want to sort.
What's the difference between this:
std::sort(str.rend(),str.rbegin())
and this:
std::sort(str.begin(),str.end())
Upvotes: 0
Views: 2767
Reputation: 227370
Assuming you intend to use std::sort
to sort the string (since neither std::vector
nor std::string
have a sort
method), the first statement is incorrect and leads to undefined behaviour (UB):
std::sort(str.rend(),str.rbegin());
Here, std::sort
will attempt to dereference str.rend()
, which is a "past the end" iterator. De-referencing such an iterator is UB.
A correct use of reverse iterators would be
std::sort(str.rbegin(),str.rend());
This would result in the string/vector being sorted in descending order.
Upvotes: 5
Reputation:
The iterators in the standard library on lots of containers and other things (like std::string
) have a reverse
variety which begin with r
(rbegin()
, rend
and the like). These will iterate in the reverse-sequential order. Using just begin
and end
will sort your string in the correct format from start to finish.
Try to avoid using the reverse iterators and just use the regular begin()
and end()
on your strings:
std::string str = "bacd";
std::sort( str.begin(),str.end() );
std::cout << str << std::endl; // should produce "abcd" on your output, without quotes
Edit:
So... you want vector<int>
to be sorted instead? If so, do the same as above, except call std::sort
with the begin()
and end()
of your std::vector<int>
.
Upvotes: 3