首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >实现等号算法

实现等号算法
EN

Stack Overflow用户
提问于 2013-11-04 18:25:37
回答 2查看 159关注 0票数 1

我所要做的就是实现平等的算法。然而,当我用几个字符串进行测试时,我会得到一个模糊错误。我认为编译器不能区分A和B。为什么会这样?

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-04 18:29:14

问题是,参数(来自std::string的迭代器)位于名称空间std中,而在这个名称空间中,由于参数依赖查找(ADL),有另一个名为equal的算法是候选的。您需要显式限定您的算法:

代码语言:javascript
运行
复制
std::cout << "a and b are " << ::equal(a.begin(), a.end(), b.begin()) << std::endl;
//                             ^^ here

请注意,C++标准不要求迭代器是std中的类型,而是允许它,您的编译器/标准库决定使用此选项。

票数 2
EN

Stack Overflow用户

发布于 2013-11-04 18:33:17

这是所谓的依赖于参数的名称查找的结果。在C++中有标准算法std::equal。编译器看到函数调用的参数属于命名空间std。因此,它还考虑到名称空间std中名称相等的任何函数。因此,它找到了两个函数:一个是由您定义的,另一个是在命名空间std中声明的。若要转义错误,请使用函数的完全限定名,即::equal。顺便说一句,您不正确地使用您的函数,这样的用法有未定义的行为。第二个范围必须至少具有与第一个范围相同的大小。在您的示例中,您使用字符串a和c,c的大小小于a的大小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19774474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档