【问题标题】:implicit instantiation of undefined template error未定义模板错误的隐式实例化
【发布时间】:2021-02-06 05:56:23
【问题描述】:

我正在使用 Programming:Principles and Practice Using C++ (2nd Edition) 来学习并遇到一些问题。 尝试下面编写的代码会给我一个未定义模板错误的隐式实例化。 我尝试添加#include<vector>,但添加代码给了我一个新的编译错误,即调用 sort() 时没有匹配的函数。

由于我知识贫乏,我找不到解决这个问题的方法,所以非常感谢给我一个解决它的建议。

#include <iostream>
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 << "Number of words:" << 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";
}

【问题讨论】:

  • 你是否创建了一个名为 sort anywhere 的函数
  • 如果您希望使用std::sort,那么您的使用不正确。 en.cppreference.com/w/cpp/algorithm/sort确实需要包含向量、字符串和算法。
  • 感谢 cmets。我尝试添加 #include&lt;algorithm&gt; #include&lt;vector&gt; #include&lt;functional&gt; #include &lt;array&gt; #include &lt;string_view&gt; 但似乎没有成功。
  • 感谢所有 cmets。修复排序方法后,一切正常!

标签: c++


【解决方案1】:

你有两个核心问题。第一个是您缺少 几个 标头:

#include <string>
#include <vector>
#include <algorithm>

string 代表 std::string,同样,vector 代表 std::vectoralgorithm 代表std::sort

第二个是 std::sort 不应该这样调用,因为它需要一对迭代器:

sort(words.begin(), words.end());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多