简体   繁体   English

std :: sort在c ++中?

[英]std::sort in c++?

I want to sort a vector using sort algorithm in C++. 我想使用C ++中的sort算法对vector进行sort

str is the name of std::vector<int> I want to sort. str是我要排序的std::vector<int>的名称。

What's the difference between this: 这有什么区别:

std::sort(str.rend(),str.rbegin())

and this: 和这个:

std::sort(str.begin(),str.end())

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对字符串进行排序(因为std::vectorstd::string都没有sort方法),第一条语句不正确,并导致未定义行为 (UB):

std::sort(str.rend(),str.rbegin());

Here, std::sort will attempt to dereference str.rend() , which is a "past the end" iterator. 在这里, std::sort将尝试取消引用str.rend() ,这是一个“过去”的迭代器。 De-referencing such an iterator is UB. 取消引用此类迭代器是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. 这将导致字符串/向量以降序排序。

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) . 标准库中许多容器和其他事物(例如std::string )上的迭代器具有以r rbegin()rend等)开头的reverse变体。 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. 仅使用beginend可以从头到尾按照正确的格式对字符串进行排序。

Try to avoid using the reverse iterators and just use the regular begin() and end() on your strings: 尝试避免使用反向迭代器,而只需在字符串上使用常规的begin()end()

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? 所以...您想对vector<int>进行排序吗? If so, do the same as above, except call std::sort with the begin() and end() of your std::vector<int> . 如果是这样,请执行上述操作,除了用std::vector<int>begin()end()调用std::sort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM