我正在從 Bjarne Stroustrup 的 Programming Principles and Practice with C 中學習 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";
}
這是書中的錯誤,還是我做錯了什么?
uj5u.com熱心網友回復:
這本書一開始就解釋說,你應該包括一個名為std_lib_facilities.h隨書而來的檔案。也可以在這里從作者的網站下載。
這是本書中用于簡化一些用于介紹語言的結構的非標準檔案。
該檔案定義了一個sort可以直接在容器上呼叫的函式。標準庫中的std::sort函式不允許這樣做。
所以添加
#include "std_lib_facilities.h"
一開始。(而且我認為您也不應該添加任何標準庫標題和您using namespace std;自己。不過我現在無法查看這本書。)
uj5u.com熱心網友回復:
直到 C 20 標準庫才提供這樣的功能。你可以std::sort這樣使用:
std::sort(words.begin(), words.end());
但是,由于這可能很煩人,因此 C 20 提供 std::ranges::sort了您想要的功能:
std::ranges::sort(words);
要使用此功能,您必須使用支持 C 20 的編譯器。
uj5u.com熱心網友回復:
sort引數必須是迭代器。代替
sort(words);
經過
sort(words.begin(), words.end());
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/451554.html
上一篇:ASP.NETMVC5:foreach回圈排序并按特定順序寫入輸出
下一篇:通過沒有共同元素進行分組?
