Using C ++ std :: equal on shared_ptr container

I have a container std :: shared_ptr. I want to compare two containers using std :: equal. Class A has the == operator. I want it to be equal if each element is equivalent using its == operator, and not the one defined in shared_ptr.

Should I make the function or function object equal? Or is there something built-in that would be simpler (for example, something defined in a <functional>)?

+4
source share
3 answers

You will need a function or function object or lambda expression (since you can use std::shared_ptr , you already have the C ++ 0x part).

There is nothing in <functional> to help you, but there is something in boost: an 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'; } 
+7
source

You can do something like the following, assuming you have a compiler that supports lambdas and that no element is null:

 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); }); } 
+3
source

I personally think that a function object will be the best choice ... everything that I saw in <functional> depends on the availability of the correct type of comparison, and this will mean if you do not want to compare that you somehow need to dereference these pointers to the objects they point to ... I don't see any helpers in the STL that automatically do this dereferencing for you.

Thanks,

Jason

0
source

Source: https://habr.com/ru/post/1346118/


All Articles