C++ 排序错误 "No instance of overloaded function.."

标签 c++ sorting vector

我对 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/

相关文章:

c++ - 函数更改 const 对象

c++ - 使用锁 xcmpchg16b _InterlockedCompareExchange128 发生读取访问冲突

c++ - 功能完美转发构建功能列表类

javascript - 创建自定义排序函数以用作脚本中的选项

r - 比较同一向量的相邻元素(避免循环)

c++ - 使用来自不同线程的 postthreadmessage()

java - 使用 Java 高效地对数据库中的数据进行排序?

javascript - 在 knockout js 或 javascript 中用斜杠对数字进行排序

c++ - 从成对 vector 中获取值时出错

r - 如何使用 seq() 和 rep() 和 paste() 生成特定向量?