std::sort()在C++;工作 我使用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"; } }
据我所知,代码片段应该排序到数组的6元素,但编译器向我显示了一个错误。所以我尝试了不同的方法让它工作。然而,只有在极客论坛中显示的方式才能工作std::sort()在C++;工作 我使用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"; } },c++,sorting,C++,Sorting,据我所知,代码片段应该排序到数组的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 t
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;
}
intmain()
{
int arr[]={1,5,8,9,6,7,3,4,2,0};
int n=sizeof(arr)/sizeof(arr[0]);
/*这里我们取两个参数,即
数组和长度n,我们希望数组达到该长度
分类*/
排序(arr,arr+n);
cout第一个例子是在C++20中工作的,如果排序来自范围名称空间。您正在阅读的书/教程中是否提到了它
sort(arr,arr[5]);
在您的术语中,arr[5]不是“where”,而是一个数组元素,即“what”。“where”是地址&arr[5]或&arr[n]。您可以使用std::begin(arr)和std::end(arr)代替arr和&arr[n]
std::sort如何工作通过上的示例进行了很好的解释。Dup解释(我认为)书中有一个特殊的标题,而不是您需要的标准库。请返回并再次阅读该章?(注释中有指向该特殊标题的链接。)抱歉,没有插入完整的代码,但我使用的是STD命名空间,为了使用这个功能,C++的新版本C++ 20有一个标准的库,叫做“范围”,可以这样做。Stroustrop可能在他的书中预想到这一点(我猜,我没有书)。。sort的那个版本不在
中。去看看另一个问题和它的注释:它会在这里为你指出正确的方向。这并没有解决问题,但只显示唯一值的循环可以用std::unique
@PeteBecker更简单地编写-这是一本书中的一个例子。一本教程。一个非常简单的例子很感谢你消除了我的误解
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;
}