'Why doesn't the compiler recognize sort with a single argument?
I am learning C++ from Bjarne Stroustrup's Programming Principles and Practice with C++. I copied the code and the compiler found an error (E0304) with the usage of 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";
}
Is this an error in the book, or am I doing something wrong?
Solution 1:[1]
The book explains at the beginning that you are supposed to include a file named std_lib_facilities.h coming with the book. It can also be downloaded from the author's website here.
This is a non-standard file used in the book to simplify some constructs for introducing the language.
This file defines a function sort that can be called directly on a container. The std::sort function from the standard library does not allow for that.
So add
#include "std_lib_facilities.h"
at the beginning. (And I think you are also not supposed to add any of the standard library headers and using namespace std; yourself either. I can't check the book right now though.)
Solution 2:[2]
Until C++20 the standard library didn't provide such a function. You can use std::sort like this:
std::sort(words.begin(), words.end());
However, since this can be annoying, C++20 provides std::ranges::sort, that does what you want:
std::ranges::sort(words);
To use this function you have to use a compiler that supports C++20.
Solution 3:[3]
sort arguments are have to be iterators. Replace
sort(words);
by
sort(words.begin(), words.end());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | churill |
| Solution 3 | Vad Sim |
