Re: Searching a vector with functionals
Matthias Buelow <mkb@incubus.de> wrote:
Hi folks,
I'm trying to implement a functor find_if, which takes a predicate, and
searches a container (for example, vector) and returns (a reference to)
the first element for which the predicate function returns true. I can't
get it to work. Maybe someone can give me a hint? From my understanding,
the call and the template-generated functions do match, typewise. The
problem appears to be that main()::f does not satisfy
std::unary_function<element_t&, bool>& but I don't understand why.
Short answer template arguments require external linkage and
local types like your struct f, do not have external linkage.
------------------------------snip------------------------------
using namespace std;
#include <functional>
#include <vector>
template<class container_t, typename element_t>
element_t &find_if(container_t &cont, unary_function<element_t &, bool>
&fun, element_t ¬found)
std::unuary function is a struct that ONLY defines types
result_type and argument_type, it has no operator () .
This is a 'short and sweet' correct version of your find_if:
template <class T,class Container,class Pred>
T & find_in(const Container &c,Pred pred,T ¬_found)
{
tyoename Container::iterator it = std::find_if
(
c.begin(),c.end(),pred);
};
return it == c.end() ? not_found:*it;
}
struct foo { int a; foo(int aa = 0): a(aa) {}; };
give f external linkage, but only file visibility.
namespace
{
{
struct f: public unary_function<foo &, bool> {
bool operator()(foo &x) {
if (123 == x.a) return true;
else return false;
}
};
}
int main()
{
vector<foo> fv;
fv.push_back(foo(1));
fv.push_back(foo(123));
fv.push_back(foo(2));
foo notfound;
foo &x = find_if(fv, f(), notfound);
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]