c++ primer之10.1 泛型概述

本文介绍C++标准库中的泛型算法,并通过示例展示了如何使用find和count算法来查找和计数容器中的元素。这些算法不直接操作容器,而是通过迭代器进行操作。

在顺序容器中,没有定义可以满足用户(程序员)所需的更多功能接口,所以标准库定义了一组泛型算法,之所以称为“泛型的”,适用于不同类型。

泛型算法一般不直接操作容器,而是遍历迭代器的元素范围来进行操作。

标准库算法find:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     cout << "Hello World!" << endl;
10 
11     int val = 42;\\要查找的值
12     vector<int> vec = {1, 32, 8, 42};
13     auto result = find( vec.cbegin(), vec.cend(), val );
14 
15     cout << "the value:" << val << ( result == vec.cend() ? " is not pressent" : " is pressent") << endl;
16 
17     return 0;
18 }

10.1 节练习

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     vector<int> vec = { 1, 9, 4, 8, 5, 5 };
10     int val = 5;
11 
12     cout << "vec == 5 有: " << count( vec.begin(), vec.end(), val );
13 
14     return 0;
15 }

10.2 节练习

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <list>
 5 
 6 using namespace std;
 7 
 8 int main()
 9 {
10     cout << "Hello World!" << endl;
11 
12     list<string> listStr = { "xcd", "chuandong", "mmd" };
13     string strVal = "xcd";
14 
15     cout << count( listStr.begin(), listStr.end(), strVal );
16 
17     return 0;
18 }

关键概念:算法永远不会执行容器的操作

{

泛型算法本身不直接执行容器的操作,而是执行迭代器的操作,而迭代器执行容器的操作。

}

 

转载于:https://www.cnblogs.com/dongdongTang/p/6670244.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值