C++学习笔记33:泛型编程拓展2
2024-10-10 05:38:20
调用标准模板库的find()函数查找数组元素
例子:
#include <iostream>
#include <algorithm>
using namespace std;
const int size = ;
int main()
{
int a[size];
for (int i = ; i < size; ++i)
{
a[i] = i;
}
int key = ;
int *ip = find(a, a + size, key);
if (ip == a + size)//不要使用NULL做指针测试,直接使用过尾元
cout << key << "not found;" << endl;
else
cout << key << "found;" << endl;
return ;
}
向量迭代器
使用向量迭代器操作向量
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int key = ;
vector<int> iv();
for (int i = ; i < ; i++)
{
iv[i] = i;
}
vector<int>::iterator it, head = iv.begin(), tail = iv.end();
it = find(head, tail, key);
if (it != tail)
cout << "vector contains the value" << key << endl;
else
cout << "vector does not contain the value" << key << endl;
return ;
}
常迭代器
若不想通过迭代器修改目标对象值,定义迭代器常量
例子:
const vector<int>::iterator it;
非法操作:*it = 10;//不能修改常迭代器指向的对象
流迭代器
使用迭代器访问流
将输入输出流作为容器
使用方式:定义流迭代器对象
实例1:ostream_iterator<int> oit(cout, " ");
实例2:(从cin获取数据):istream_iterator<int>iit(cin);
实例3:(使用空指针创建流结束迭代器):
istream_iterator<int> iit;
凡是可以出现迭代器参数的标准算法都可以使用
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include "random.h"
using namespace std;
const int size = ;
const int lower_bound = ;
const int upper_bound = ; void Display(vector<int> &v, const char *s)
{
cout << endl << s << endl;
vector<int>::iterator head = v.begin(), tail = v.end();
ostream_iterator<int> oit(cout, ";");
copy(head, tail, oit);
cout << endl;
}
int main()
{
vector<int> a(size);
for (int i = ; i < size; ++i)
{
a[i] = GenerateRandomNumber(, );
}
Display(a, "Array generated:");
vector<int>::iterator head = a.begin(), tail = a.head();
sort(head, tail);
Display(a, "Array sorted:");
reverse(head, tail);
Display(a, "Array reversed;");
return ;
}
最新文章
- Git------Win7系统使用TortoiseGit
- 【转】Kylin中的cube构建
- POJ1201 Intervals
- 未能加载文件或程序集“System.Web.Razor”或它的某一个依赖项。文件或目录损坏且无法读取。
- 阿里云ECS(linux)磁盘满触发的mysql的表异常修复案例
- Ruby学习: 全局变量 和常量
- C#入门经典第七章,错误调试
- 浅谈IM(InstantMessaging) 即时通讯/实时传讯【理论篇】
- IntelliJ IDEA 使用教程
- AJAX返回值问题
- ajax上传下载自定义圆形滚动条
- Codeforces round 1098
- 巧用NULL模式解耦依赖
- cobbler-web 界面技术详解
- 让CI框架支持service层
- Eclipse 中导入jar包
- SQL的 like 中间字符通配 用法
- Java内存模型(转载)
- JavaScript闭包的特性
- POJ 3532 Resistance(高斯消元+基尔霍夫定理)