首页 / C++ / C++ 之 函数对象
C++ 之 函数对象
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++ 之 函数对象,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1518字,纯文字阅读大概需要3分钟。
内容图文
参考 https://blog.csdn.net/xgf415/article/details/52966475
推荐这篇文章写的基础总结, 为了方便理解, 完善了文章中的示例代码, 在此记录一下
#include <string>
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
class relu {
public:
int operator() (int val) {
return val > 0 ? val : -val;
}
};
class Sort {
public:
bool operator() (const std::string &str1, const std::string &str2) const {
return str1 > str2;
}
};
class Upper {
public:
Upper(int min = 0) : m_min(min) {}
bool operator() (int value) const {
return value >= m_min;
}
private:
int m_min;
};
class Count {
public:
Count(int n = 0) : th(n), count(1) {}
bool operator() (int) {
return count++ == th;
}
int getCount() const {
return count;
}
private:
int th;
int count;
};
int main() {
int i = -1;
relu relu_func;
std::cout << relu_func(i) << std::endl;
std::set<std::string, Sort> myset;
myset.insert("A");
myset.insert("B");
for (std::set<std::string, Sort>::iterator iter = myset.begin(); iter != myset.end(); iter++) {
std::cout << *iter << std::endl;
}
Upper upper(3);
std::cout << upper(4) << std::endl;
std::vector<int> vec;
for (int i = 3; i != 13; i++) {
vec.push_back(i);
}
Count count(3);
std::vector<int>::iterator iter = find_if(vec.begin(), vec.end(), count);
std::cout << "found: " << *iter << std::endl;
std::cout << "state: " << count.getCount() << std::endl;
int less_equal_10_count = std::count_if(vec.begin(), vec.end(), std::bind2nd(std::less_equal<int>(), 10));
std::cout << "less equal 10, found " << less_equal_10_count << std::endl;
}
内容总结
以上是互联网集市为您收集整理的C++ 之 函数对象全部内容,希望文章能够帮你解决C++ 之 函数对象所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。