c++ - 实现相等算法

标签 c++ 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;
}

主要内容

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;

错误信息

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 中的类型,但允许它并且您的编译器/标准库决定使用此选项。

关于c++ - 实现相等算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19774474/

相关文章:

c++ - Asm CALL 指令 - 它是如何工作的?

c++ - 在 C++ Builder 中覆盖事件处理程序

algorithm - 哈希数字向量的方法?

将节点分配给图形的算法设计

algorithm - 简单/基本的隐写算法和方法

algorithm - 如何使用智能手机加速度计的样本计算距离?

c++ - 如何在不将查找表加载到内存的情况下对查找表执行搜索?

由 C++ Python 3 绑定(bind)

c# - 如何连接点和吸收动量?

c++ - 模板类模板构造函数特化