我对 C++ 和一般编程还是很陌生,所以如果第一次没有正确的信息,我深表歉意
我开始学习如何使用 Bjarne Stroustrup 编写的“编程:使用 C++ 的原理和实践(第 2 版)”一书进行编码,但在使用第 4.6.4 章中提供的代码时遇到了一些错误。每次我运行代码时,它都会告诉我有关“std::sort”的信息,并且没有重载函数“std::sort”的实例与参数列表匹配。第 16 行中还有一个新错误 i-1,因为 IDE (Visual Studio 2013 Express) 表示标识符未定义。
#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";
}
我似乎无法找出导致错误的原因,因为我已经输入了所需的#include,但它仍然显示错误。任何解释都会有很大帮助。
最佳答案
std::sort 采用一对迭代器。
std::sort(words.begin(), words.end());
您可以定义自己的带有一个参数的辅助函数。
template<typename Container>
inline void sort(Container& c)
{
std::sort(std::begin(c), std::end(c));
}
您可能想为辅助函数创建自己的命名空间。
关于C++ 排序错误 "No instance of overloaded function..",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491584/