Using C++ std::equal on a container of shared_ptr
I have a container of std::shared_ptr. I want to compare two containers using std::equal. The class A has operator== defined. I want equal to compare if each element is equivalent using its operator==, not the one defined in shared_ptr.开发者_StackOverflow社区
Do I need to make a function or function object to pass to equal? Or is there something built-in that would be simpler (like something defined in <functional>)?
You will need a function or a function object or a lambda expression (since you're able to use std::shared_ptr
, you have some part of C++0x already enabled).
There is nothing in <functional>
to help you, but there is something in boost: the 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';
}
You could do something like the following, assuming you have a compiler that supports lambdas and that no items are ever 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);
});
}
I'm personally thinking the function object would be the best bet ... everything that I've seen in <functional>
depends on having the correct comparison type, and that would mean if you didn't want to compare the pointers themselves, that you would somehow need a dereference of those pointers to the objects they're pointing to ... I don't see any helpers in the STL that automatically do that dereference for you.
Thanks,
Jason
精彩评论