I'm trying to find an element in a std::vector based in a member function, but unforunately I have no access to a full C++11 conformant compiler.
I kwnow I can use a functor to solve this, but I wonder if there is a "functional" way to accomplish the same result.
Below is a snippet which depicts my problem:
#include <iostream>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
struct Class {
int type_;
Class(int type): type_(type) {
}
int GetType() {
return type_;
}
};
struct Functor {
Functor(int t): t_(t) {
}
bool operator()(Class c) {
return c.GetType() == t_;
}
int t_;
};
int main() {
// It also works
std::vector<Class> v2 { Class(1), Class(2), Class(3), Class(4), Class(5) };
auto it2 = std::find_if(v2.begin(), v2.end(), Functor(4));
std::cout << (it2 != v2.end() ? "Found!" : "Not found!") << std::endl;
// It would solve, but I can't use due to compiler limitations :(
it2 = std::find_if(v2.begin(), v2.end(), [](auto& v) { return v.GetType() == 4; });
std::cout << (it2 != v2.end() ? "Found!" : "Not found!") << std::endl;
// Is there any "functional based" solution to this, using std::mem_fun, std::bind1st, etc.?
// it2 = std::find_if(v2.begin(), v2.end(), ???);
return 0;
}
if my std::vector was formed by a non-complex type, I would do something like:
std::vector<int> v1 { 1, 2, 3, 4, 5 };
auto it1 = std::find_if(v1.begin(), v1.end(), std::bind1st(std::equal_to<int>(), 4));
std::cout << (it1 != v1.end() ? "Found!" : "Not found!") << std::endl;
Is there any solution do write a code similar to that above?
Edit:
I'm using GCC 4.4.1
Edit2:
Based in some comments and in the response from @scohe001, I would solve the problem overloading the global == operator.
But my curiosity isn't satisfied yet :)
Is there no way to achieve my goal using the std toolset from <funtional>
?
Edit3:
Only to clarify: After reading the responses and comments, I know that it's possible to solve the simple example I posted before using the overloading of the operator==(int)
and also know that I can use a function object (functor)
to do the same job of the lambda expression. But, my real question is: Using ONLY the toolset available in <functional>
(std::mem_fun, std::bind1st, std::equal_to, etc), can I "mimic" the behavior of the lambda/functor? If so, how can I "chain" the funtion calls to do it?
Edit4:
Apparently there's no way to solve my problem ONLY using the existing toolset from <functional>
, so I'm accepting the @Caleth
's response, once it's the one which is closer to what I was trying to do.