Created
June 6, 2011 14:08
-
-
Save mizutomo/1010332 to your computer and use it in GitHub Desktop.
C++ template with functor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <algorithm> | |
#include <iostream> | |
class Hage | |
{ | |
public: | |
float val; | |
Hage() {} | |
Hage(float _val) { val = _val; } | |
}; | |
template <class T> | |
class Cmp | |
{ | |
private: | |
T hoge; | |
public: | |
bool operator()(const T& a, const T& b); | |
}; | |
template<class T> bool Cmp<T>::operator()(const T& a, const T& b) | |
{ | |
if (a.val < b.val) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
int main() | |
{ | |
Cmp<Hage> cmp_obj; | |
std::vector<Hage> nums; | |
for (int i = 5; i > 0; i--) { | |
nums.push_back(Hage(static_cast<float>(i + 0.5f))); | |
} | |
std::sort(nums.begin(), nums.end(), cmp_obj); | |
for (std::vector<Hage>::iterator iter = nums.begin(); iter != nums.end(); iter++) { | |
std::cout << iter->val << std::endl; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment