[英]Why doesn't the compiler recognize sort with a single argument?
我正在使用 C++ 從 Bjarne Stroustrup 的編程原理和實踐中學習 C++。我復制了代碼,編譯器在使用sort(words)
。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main() {
vector<string> words;
for (string temp; cin >> temp; )
words.push_back(temp);
cout << " Word count : " << words.size() << ' \n ';
sort(words);
for (int i = 0; i < words.size(); ++i)
if (i == 0 || words[i - 1] != words[i])
cout << words[i] << "\n";
}
這是書上的錯誤,還是我做錯了什么?
這本書在開頭解釋說,您應該在本書中包含一個名為std_lib_facilities.h
的文件。 也可以從作者的網站下載。
這是本書中使用的非標准文件,用於簡化介紹該語言的一些結構。
該文件定義了一個 function sort
,可以直接在容器上調用。 標准庫中的std::sort
function 不允許這樣做。
所以添加
#include "std_lib_facilities.h"
一開始。 (而且我認為您也不應該添加任何標准庫標頭和using namespace std;
您自己也一樣。不過我現在無法查看這本書。)
直到 C++20,標准庫才提供這樣的 function。您可以像這樣使用std::sort
:
std::sort(words.begin(), words.end());
然而,由於這可能很煩人,C++20 提供了std::ranges::sort
,它可以做你想做的:
std::ranges::sort(words);
要使用這個 function 你必須使用支持 C++20 的編譯器。
sort
arguments 必須是迭代器。 代替
sort(words);
經過
sort(words.begin(), words.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.