2015-06-19 56 views
7
#include <algorithm> 
#include <vector> 

template <class BidirectionalIterator, class UnaryPredicate> 
BidirectionalIterator partition(BidirectionalIterator first, 
    BidirectionalIterator last, UnaryPredicate pred) 
{ 
    while (first != last) { 
     while (pred(*first)) { 
      ++first; 
      if (first == last) return first; 
     } 
     do { 
      --last; 
      if (first == last) return first; 
     } while (!pred(*last)); 
     std::swap(*first, *last); 
     ++first; 
    } 
    return first; 
} 

int main() { 
    std::vector<int> v = { 1, 55, 17, 65, 40, 18, 77, 37, 77, 37 }; 
    partition(v.begin(), v.end(), [](const int &i) { 
     return i < 40; 
    }); 
    return 0; 
} 

代碼不會編譯。 clang ++(3.5.2/cygwin)和Visual Studio(2013)都抱怨模糊的調用。由於沒有使用using指令,我不明白什麼是錯的。 要成功編譯,使用::前綴有幫助。鐺++:錯誤:調用'分區'含糊

回答

8

partition有一個名字碰撞std::partition

它這樣做的理由,即使沒有std::前綴是因爲它是在爭論,這是std::vector<int>::iterator,它搭載了std::命名空間使用argument dependent lookup (ADL)。因此,編譯器能夠「看到」std::partition函數以及partition函數。

From cppreference(重點煤礦)

... for every argument in a function call expression and for every template argument of a template function, its type is examined to determine the associated set of namespaces and classes that it will add to the lookup