Reputation: 67
I'm still very new to C++ and programming in general, so I apologize if haven't the right information the first time
I started learning how to code with the book "Programming: Principles and Practice Using C++ (2nd Edition)" by Bjarne Stroustrup and I ran into some errors while using the code provided in chapter 4.6.4. Every time I go to run the code it tells me about "std::sort" and that there's no instance of overloaded function "std::sort" matches the argument list. There's also a new error in line 16 with i-1 as the IDE (Visual Studio 2013 Express) says the identifier is undefined.
#include <iostream>
#include <string>
#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() << std::endl;
std::sort(words);
for (int i = 0; i<words.size(); ++i)
if (i == 0 || words[i–1] != words[i]) // is this a new word?
std::cout << words[i] << "\n";
}
I can't seem to find out what's causing the error as I've put the required #include but it still shows the error. Any explanation would help tremendously.
Upvotes: 3
Views: 4012
Reputation: 484
std::sort takes a pair of iterators.
std::sort(words.begin(), words.end());
You could define your own helper function that takes one argument.
template<typename Container>
inline void sort(Container& c)
{
std::sort(std::begin(c), std::end(c));
}
You probably want to create your own namespace for the helper function.
Upvotes: 4