实现相等算法

Implementing equal algorithm

本文关键字:算法 实现      更新时间:2023-10-16

我要做的就是实现相等算法。但是,当我使用几个字符串进行测试时,我得到一个歧义错误。我认为编译器无法区分 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 的大小。