c++ - 实现 equal() 和 find()

标签 c++ argument-dependent-lookup

在下面的代码中,我必须限定 equal() 调用(否则我会得到“对重载函数的不明确调用”),但可以调用不限定的 find()。有什么区别?

#include <iterator>
#include <vector>
#include <iostream>

using std::vector;
using std::cout;
using std::endl;

// Test whether the elements in two ranges are equal.
// Compares the elements in the range [b,e) with those in the range
// beginning at d, and returns true if all of the elements in both ranges match.
template <class InIter1, class InIter2>
bool equal(InIter1 b, InIter1 e, InIter2 d)
{
    cout << "My equal()" << endl;
    while (b != e)
        if ((*b++) != (*d++))
            return false;
    return true;
}

// Returns an iterator to the first element in the range [b,e)
// that compares equal to t. If no such element is found, the function returns last.
template <class InIter, class T>
InIter find( InIter b, InIter e, const T& t )
{
    cout << "My find()" << endl;
    while (b != e) {
        if ( *b == t )
            return b;
        b++;
    }

    return e;
}

/* "Accelerated C++", ex. 8.2 */
int main()
{
    static const int arr[] = {8, 7, 15, 21, 30};
    vector<int> vec(arr, arr + sizeof(arr) / sizeof(arr[0]) );

    cout << "equal() result: " << ::equal(vec.begin(), vec.end(), vec.rbegin()) << endl;

    vector<int>::iterator iter = find(vec.begin(), vec.end(), 21);
    if (iter == vec.end())
        cout << "did not find()" << endl;
    else
        cout << "find() result: " << *iter << endl;

    return 0;
}

我认为它与参数依赖查找有关(请参阅 this question ),但仍然不明白为什么这两个调用不同。

最佳答案

看来您的标准库实现带来了 std::equal来自其他一些文件,该文件也没有引入 std::find (也许它用于 vector 的比较运算符)。如果您包括 <algorithm> ,它们都会被引入,并且两种情况都会含糊不清。

关于c++ - 实现 equal() 和 find(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724178/

相关文章:

C++:循环依赖问题

c++ - 从 char 转换为 string 时丢失编码

c++ - 链接隐式转换运算符

c++ - 对于类型为类模板特化的参数,ADL 背后的基本原理是什么

c++ - 什么是 "Argument-Dependent Lookup"(又名 ADL,或 "Koenig Lookup")?

c++ - 没有模板的 ADL

c++ - 指定应调用非成员函数而不是成员函数

c++ - 2 个值的容器(对于每个 float 一个可操作的整数)

c++ - Win32 上的 LAPACK

c++ - 模板类中友元运算符的多重定义