54函数对象

it2025-05-06  6

54函数对象

基本概念示例代码

基本概念

重载函数调用操作符()

函数对象:定义了调用操作符的类,其对象称为函数对象

一元函数对象与一元谓词(函数对象返回值是bool类型,有一个参数)

二元函数对象与二元谓词(函数对象返回值是bool类型,有两个参数)

示例代码

#include <iostream> #include <map> #include <string> using namespace std; int main() { map<int, string> a; //定义map map<string, int> grade; multimap<int, string> ma; //插入数据 key键 value值 a.insert(map<int, string>::value_type(1, "One")); a.insert(map<int, string>::value_type(2, "Two")); a.insert(map<int, string>::value_type(3, "Three")); a.insert(make_pair(-1, "Minus One")); //使用make_pair函数 a.insert(pair<int, string>(1000, "One thousand")); //使用pair a[1000000] = "One Million"; //使用下标 grade.insert(make_pair("张飞", 99)); grade.insert(make_pair("刘备", 56)); grade["关羽"] = 87; cout << "最简单的查找:" << endl; cout << a[3] << endl; cout << grade["刘备"] << endl; cout << "map里一共有" << a.size() << "个key_value对数据" << endl; cout << "这些数据是:" << endl; map<int, string>::const_iterator i; for(i = a.begin(); i != a.end(); ++i) { cout << "Key:" << i->first; cout << " Value: " << i->second.c_str() << endl; } ma.insert(multimap<int, string>::value_type(3, "Three")); ma.insert(multimap<int, string>::value_type(45, "Forty Five")); ma.insert(make_pair(-1, "Minus One")); ma.insert(pair<int, string>(1000, "One thousand")); ma.insert(pair<int, string>(1000, "One thousand")); //multimap可以重复数据 //multimap不能使用下标插入数据! cout << endl << "multimap里有" << ma.size() << "个数据" << endl; multimap<int, string>::const_iterator i2; for(i2 = ma.begin(); i2 != ma.end(); ++i2) { cout << "Key:" << i2->first; cout << " Value: " << i2->second.c_str() << endl; } cout << endl << "multimap里有" << ma.count(1000) << "个1000" << endl; //find查找,通过迭代器查找 multimap<int, string>::const_iterator fi; fi = ma.find(45); if(fi != ma.end()) { cout << "找到了:" << fi->first << " = " << fi->second.c_str() << endl; } else { cout << "没找到!" << endl; } fi = ma.find(1000); //查找重复的数据 if(fi != ma.end()) { cout << "找到了1000!" << endl; size_t n = ma.count(1000); for(size_t i = 0; i < n; ++i) { cout << "\t Key: " << fi->first; cout << ", Value [" << i << "] = " << fi->second.c_str() << endl; ++fi; } } else { cout << "没找到1000!" << endl; } //erase删除操作 if(ma.erase(-1) > 0) cout << endl << "删除-1成功!" << endl; //通过迭代器删除 multimap<int, string>::iterator iElementFound = ma.find(45); if(iElementFound != ma.end()) { ma.erase(iElementFound); cout << "删除45成功!" << endl; } //通过键值对删除一个范围 ma.erase(ma.lower_bound(1000), ma.upper_bound(1000)); return 0; }
最新回复(0)