Reputation: 73
I have also copied the exact code from Programming Principles & Practice but to no avail.
I get an error message when I try to use std::sort(word)
or sort(word)
:
<source>: In function 'int main()':
<source>:13:14: error: no matching function for call to 'sort(std::vector<std::__cxx11::basic_string<char> >&)'
13 | std::sort(words);
| ~~~~~~~~~^~~~~~~
[...]
The code:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<std::string> words;
for(std::string temp; std::cin >> temp;){
words.push_back(temp);
}
std::cout << "Number of words: " << words.size() << "\n";
std::sort(words);
for(int i=0; i < words.size(); i++){
if(i == 0; words[i-1]!=words[i]){
std::cout << words[i] << "\n";
}
}
}
Upvotes: 1
Views: 176
Reputation: 517
sort function accepts either 2 or 3 variables. first 2 are for starting and ending indexes. In this case, they are words.begin() and words.end()
So, your 13th line (which has the error) should be:
std::sort(words.begin(),words.end());
The 3rd argument can be given to specify type of sort. For example,
std::sort(words.begin(),words.end(),greater<int>());
will sort the vector in reverse order.
Upvotes: 2
Reputation: 50774
There are two problems in your code:
your usage of sort
is wrong, it's std::sort(words.begin(), words.end())
. This should be in your book or in your learning material.
in if (i == 0; words[i-1]!=words[i])
during the first iteration i
is 0 and therefore you are accessing words[-1]
which is out of bounds and which will at best trigger some error message. Also the ;
makes no sense here.
You probably want this:
for (size_t i = 0; i < words.size() - 1; i++) {
if (words[i] != words[i + 1]) {
std::cout << words[i] << "\n";
}
}
Upvotes: 3