实现相等算法
Implementing equal algorithm
我要做的就是实现相等算法。但是,当我使用几个字符串进行测试时,我得到一个歧义错误。我认为编译器无法区分 A 和 B。这是为什么呢?
template <class A, class B> bool equal(A beg, A end, B out)
{
while(beg != end) {
if(*beg == *out) {
++beg;
++out;
}
else return false;
}
return true;
}
MAIN
std::string a("This is a string");
std::string b("This is a string");
std::string c("String c");
std::cout << "a and b are " << equal(a.begin(), a.end(), b.begin()) << std::endl;
std::cout << "a and c are " << equal(a.begin(), a.end(), c.begin()) << std::endl;
ERROR MESSAGE
procedures_main.cpp:17:35: error: call to 'equal' is ambiguous
std::cout << "a and b is " << equal(a.begin(), a.end(), b.begin()) << std::endl;
^~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/algorithm:1105:1: note:
candidate function [with _InputIterator1 = std::__1::__wrap_iter<char *>, _InputIterator2 =
std::__1::__wrap_iter<char *>]
equal(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2)
^
./procedures.hpp:73:34: note: candidate function [with A = std::__1::__wrap_iter<char *>, B = std::__1::__wrap_iter<char
*>]
template <class A, class B> bool equal(A beg, A end, B out)
问题是参数(来自 std::string
的迭代器)位于命名空间std
中,并且在此命名空间中,还有另一种称为 equal
的算法,由于参数相关查找 (ADL),它是候选算法。您需要显式限定您的算法:
std::cout << "a and b are " << ::equal(a.begin(), a.end(), b.begin()) << std::endl;
// ^^ here
请注意,C++ 标准不要求迭代器是 std
中的类型,但允许它并且您的编译器/标准库决定使用此选项。
这是所谓的参数相关名称查找的结果。有标准算法 std::等于 C++。编译器看到函数调用的参数属于命名空间 std。因此,它还考虑了命名空间 std 中名称相等的任何函数。结果,它找到两个函数:一个由您定义,另一个在命名空间 std 中声明。要转义错误,请使用函数的完全限定名 ::equal。顺便说一下,您错误地使用函数,并且这种用法具有未定义的行为。第二个范围的大小必须至少与第一个范围的大小相同。在您的示例中,wnen 您使用字符串 a 和 c,c 的大小小于 a 的大小。
相关文章:
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何检查 CNG Windows API 是否返回符合 FIPS 的算法实现
- 递归合并排序算法实现
- OpenGL:布雷森汉姆的线条绘制算法实现
- 微小加密算法实现会产生意想不到的结果
- 在c++中使用合并排序算法实现计数反转
- 我正在尝试为 Kruskal 算法实现一个C++程序,该程序需要我按权重对图形进行排序。如何按权重对结构进行排序
- 最近点对O(nlogn)算法——c++实现中的一些数据问题
- 算法实现错误(DFS)
- 如何为涉及对象成员、间接寻址和强制转换的排序算法实现lambda函数
- 算法实现与 C++ 和 PHP 进行比较
- 如何仅使用 stl 算法实现此函数
- 三边化(2D)算法实现
- 扩展 Dijkstra 算法实现
- 使用霍夫曼树解码算法/实现
- 弗洛伊德-沃歇尔算法实现的问题
- OpenCV中的自适应算法实现
- 克鲁斯卡尔的算法实现
- 用于选择随机子集的通用算法实现
- 非递归 Kosaraju 的两次传递算法实现需要很长时间才能在大型数据集上执行