c++ - 没有匹配函数调用“...”涉及模板化函数的编译器错误
问题描述
我正在做一个项目,我在其中制作各种算法,例如整数的计数和排序,然后我将它们转换为模板函数,以便它们可以与向量和列表等内容一起使用。
例如,一个模板函数如下所示:
template<typename Iter>
int count(Iter* first, Iter* limit, int value)
{
int counter = 0;
while(first != limit)
{
if(*first == value)
++counter;
++first;
}
return counter;
}
当我在我的代码中运行一些代码时,main.cpp
例如:
std::vector<int> a = {0, 0, 2, 4, 2, 0};
//I expect count to return 3 for this call...
cout << count(a.begin(), a.end(), 0) << "\n";
它给了我一个编译器错误:
error: no matching function for call to ‘count(std::vector<int>::iterator, std::vector<int>::iterator, int)’
cout << count(a.begin(), a.end(), 0) << "\n";
我真的试图自己解决这个问题,但这对我来说没有意义。我有另一种称为从到print
打印向量的算法,它工作得非常好。我尝试在有效的和无效的之间建立联系,但对我来说没有任何逻辑意义。vec.begin()
vec.end()
跟进:可能是*
我的函数定义中的问题吗?也许是因为我有(Iter *first, Iter *last)
而不是(Iter first, Iter last)
?
解决方案
是的*
,你的参数是问题所在。迭代器不是指针,而是旨在模仿指针(另一方面,指针可以是有效的迭代器)。不要通过指针传递迭代器,而是通过值传递它们,例如:
template<typename Iter>
int count(Iter first, Iter limit, int value)
{
int counter = 0;
while (first != limit)
{
if (*first == value)
++counter;
++first;
}
return counter;
}
附带说明一下,标准 C++ 库已经有一个算法,可以做你的函数所做std::count()
的同样的事情:count()
#include <vector>
#include <algorithm>
std::vector<int> a = {0, 0, 2, 4, 2, 0};
cout << std::count(a.begin(), a.end(), 0) << "\n";
推荐阅读
- orientdb - OriendDB如何解决delete而不是delete的顶点问题
- html - 如何在与 CSS 网格一起滚动时将边框固定在主体上?
- javascript - 使用 Google Apps 脚本文件将项目映射到 html 文件
- smtp - 绕过 gmail 设备验证
- java - 司机考试多项选择数组while循环提示学生答题方法
- c# - 以编程方式发送的电子邮件不存储在“已发送邮件”文件夹 ASP.Net
- python - 如何在 sqlalchemy 中通过布尔条件选择不同的值
- java - 从mysql数据库列接收某些数据后,如何在recyclerview中更改特定卡的颜色
- couchbase - Couchbase - 更新自引用文档中的子项 (N1QL)
- amazon-web-services - S3 API 错误:访问被拒绝 AWS RDS LOAD DATA 从 S3 到 RDS