C++中的std::sort()函数是如何工作的



我正在使用编程原理和实践使用C++作为我学习编程和C++的指南和参考。在第4.6.4章中,本书展示了这段代码。

int main()
{
vector<string> words;
for (string temp; cin >> temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
cout << "Number of words: " << words.size() << 'n';
sort(words); // sort the words
for (int i = 0; i < words.size(); ++i)
{
if (i == 0 || words[i-1] != words[i]) // is this a new word?
cout << words[i] << "n";
}
}

在这个例子中,排序函数显示了错误,所以我在谷歌上搜索了一下,以更好地理解排序函数,根据我的理解,排序函数的第一个周长包含要排序的数组或向量,第二个变量告诉排序函数将其排序到哪里

int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
sort(arr, arr[5]);
}

根据我的理解,代码片段应该排序到数组的6元素,但编译器显示了一个错误。所以我尝试了不同的方法来让它发挥作用。然而,只有在极客论坛工作的方式显示极客。

int main()
{
int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
sort(arr, arr + n);
cout << "nArray after sorting using "
"default sort is : n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}

有人能解释一下的工作原理吗

如果排序来自range命名空间,则第一个示例在C++20中工作。你正在读的书/教程中提到了吗?

sort(arr, arr[5]);在你的条件下,arr[5]不是";其中";,它是一个数组元素;什么"其中";是地址&arr[5]或&arr[n]。您可以使用std::begin(arr(和std::end(arr;arr[n]。

通过std::sort的例子,我们很好地解释了std::排序的工作原理。

最新更新