2011-03-31 89 views
4

我有一個std :: shared_ptr的容器。我想用std :: equal來比較兩個容器。類A定義了operator ==。如果每個元素使用其運算符==相等,則我想要等於比較,而不是在shared_ptr中定義的那個。在shared_ptr的容器上使用C++ std :: equal

我是否需要將函數或函數對象傳遞給平等?還是有內置的東西會更簡單(如<功能>中定義的東西)?

回答

7

您將需要一個函數或函數對象或lambda表達式(自你可以使用std::shared_ptr,你已經啓用了C++ 0x的一部分)。

中沒有任何<functional>來幫助你,但也有一些是在提升:在indirect iterator

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <memory> 
#include <boost/iterator/indirect_iterator.hpp> 
int main() 
{ 
     std::vector<std::shared_ptr<int>> v1; 
     std::vector<std::shared_ptr<int>> v2; 
     v1.emplace_back(new int(1)); 
     v2.emplace_back(new int(1)); 

     bool result = 
      std::equal(boost::make_indirect_iterator(v1.begin()), 
         boost::make_indirect_iterator(v1.end()), 
         boost::make_indirect_iterator(v2.begin())); 
     std::cout << std::boolalpha << result << '\n'; 
} 
+0

謝謝,但我一直在避免添加提升依賴項。太糟糕了,這正是我想要的... – Matt 2011-03-31 19:07:56

+0

@Matt:你總是可以編寫自己的解引用迭代器,http://stackoverflow.com/questions/352152/is-there-a-dereference-iterator-in-the-stl/352162#352162 – Cubbi 2011-03-31 19:09:55

+0

很酷,我想我仍然會使用函數對象,因爲在這種情況下它很簡單,但如果在此之後我需要類似的功能,那麼這是一個有趣的想法。 – Matt 2011-03-31 19:12:54

3

你可以做類似下面,假設你有一個支持lambda表達式編譯器,並沒有項目過空:

bool CompareA(const vector<shared_ptr<A>>& first, 
       const vector<shared_ptr<A>>& second) { 

    return equal(first.begin(), first.end(), second.begin(), 
       [](const shared_ptr<A>& item1, const shared_ptr<A>& item2) -> bool{ 
        return (*item1 == *item2); 
       }); 
} 
+0

也許是更好的通過const引用傳遞'shared_ptr'的,因爲它們複製是有點貴。 – Cubbi 2011-03-31 19:16:26

+0

@Cubbi誠然,它也不必要地增加了引用計數。更改了代碼。 – bsruth 2011-03-31 21:19:52

0

我個人想的函數對象將是最好的選擇...一切,我已經在<functional>中看到依賴於具有正確的比較類型,這將意味着如果你不想比較指針本身,你會以某種方式需要對指向它們指向的對象的指針進行解引用...我不知道沒有看到STL中的任何助手會自動爲你解除引用。

感謝,

傑森

+0

是的,這就是我想要的,我不認爲它存在,但也許我錯過了一些東西。 – Matt 2011-03-31 19:04:57

相關問題