实现equal()和find()

时间:2013-12-21 22:26:05

标签: 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),但仍然不明白为什么这两个调用是不同的。

1 个答案:

答案 0 :(得分:2)

您的标准库实现似乎会从其他文件中引入std::equal,这些文件也不会引入std::find (可能它用于向量的比较运算符)。如果你加入<algorithm>,它们都会被引入,你会对这两种情况产生歧义。