C++泛型编程到底有多么强大?最近研究了一些基本的类库,今天来记录和分享一下自己的学习成效。map这个关联性容器其实就相当于python当中的键值对,也就是字典。这里可以有一个疑问,字典这个理念最新是在哪种编程语言中产生的呢?
首先我们来看一下需要包含的头文件:
#include<iostream>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
其次我们定义一个类似函数的结构体(也就是仿函数),实现简单的打印操作,代码如下:
struct Display
{//仿函数,重载()运算符
void operator()(pair<string, double> info)
{
cout << info.first << " " << info.second;
cout<< endl;
}
};
再次是main()核心代码部分,程序里面都有相应的注释。
int main()
{
map<string, double>studentSocres;//定义一个学生成绩的字典
studentSocres["Ligang"] = 96.2; //第一种赋值的方法
studentSocres["Lixia"] = 97.3;
studentSocres.insert(pair<string, double>("Zhangsan", 98.6));//第二种赋值的方法
studentSocres.insert(pair<string, double>("Hanmeimei", 95.6));
studentSocres.insert(pair<string, double>("Wangwu", 92.6));
studentSocres.insert(map<string, double>::value_type("Zhangsan", 98.6));//第三种赋值的方法
for_each(studentSocres.begin(), studentSocres.end(), Display());//利用for_each遍历字典
//利用迭代器和find方法查找字典元素
map<string, double>::iterator iter;
iter = studentSocres.find("Zhangsan");
if (iter != studentSocres.end())
{
cout << "找到这个人的成绩是:" << iter->second << endl;
}
else cout << "没有找到这个人" << endl;
return 0;
}
运行结果如下:
Hanmeimei 95.6
Ligang 96.2
Lixia 97.3
Wangwu 92.6
Zhangsan 98.6
找到这个人的成绩是:98.6
最后总结一下,程序看上去并不复杂,但是涉及的编程知识不少,更能体现C++泛型编程思想和理念的必要和强大之处。融入了map关联性容器的使用方法和三种赋值方法,for_each()的遍历方法,在IDE中可以查看定义去感受它的实现方法,利用结构体重载()运算符,体现仿函数的一种典型思维,这是一种灵活的处理方法,更体现泛型编程的灵活性和高耦合性。迭代器的使用在C++项目开发中也是一种金典的泛型编程理念。