简体   繁体   English

具有相同参数的 C++ std::sort

[英]C++ std::sort with identical arguments

I'm reading someone else's code, and I see something like this:我正在阅读别人的代码,我看到如下内容:

sort(myvec.begin(),  myvec.begin());

I wrote some code to test it, and it seems to do the same thing as我写了一些代码来测试它,它似乎和

sort(myvec.begin(),  myvec.end());

Do they really do the same thing?他们真的做同样的事情吗? Is that documented?有记录吗? Is there a way to understand why, or was it just an arbitrary choice to implement it in that way?有没有办法理解为什么,或者以这种方式实现它只是一个随意的选择?

Update after answers回答后更新

Yes, it's a no-op.是的,这是一个无操作。 My test code had a bug.我的测试代码有一个错误。

The code代码

sort(myvec.begin(),  myvec.begin());

should be a no-op, since that's an empty range.应该是空操作,因为这是一个空范围。 The code代码

sort(myvec.begin(),  myvec.end());

will sort the entire contents of myvec .将对myvec的全部内容进行排序。 If these happen to do the same thing, it means that your vector was already sorted.如果这些碰巧做同样的事情,这意味着你的向量已经排序。 The first line is almost certainly a typo or a bug waiting to happen.第一行几乎可以肯定是打字错误或等待发生的错误。

Iterators are just a way of specifying range.迭代器只是指定范围的一种方式。 You must have bad intuitions about them if you have even thought that this code could work properly.如果您甚至认为此代码可以正常工作,那么您一定对它们有不好的直觉。 What if we used method that takes 2 indices -> begin index of the part of vector being sorted and the index indicating end of it.如果我们使用采用 2 个索引的方法 -> 正在排序的向量部分的开始索引和指示它结束的索引怎么办。 Would sort(0, myvec.size()) and sort(0, 0) be equivalent? sort(0, myvec.size())sort(0, 0)是等价的吗?

This code should undoubtly be sort(myvec.begin(), myvec.end());毫无疑问,这段代码应该是sort(myvec.begin(), myvec.end());

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

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