C++学习笔记33:泛型编程拓展2

调用标准模板库的find()函数查找数组元素

例子:

#include <iostream>
#include <algorithm>
using namespace std;
const int size = 16;
int main()
{
    int a[size];
    for (int i = 0; i < size; ++i)
    {
        a[i] = i;
    }
    int key = 7;
    int *ip = find(a, a + size, key);
    if (ip == a + size)//不要使用NULL做指针测试,直接使用过尾元
        cout << key << "not found;" << endl;
    else
        cout << key << "found;" << endl;
    return 0;
}

向量迭代器

使用向量迭代器操作向量

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
    int key = 7;
    vector<int> iv(10);
    for (int i = 0; i < 10; 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 0;
}

常迭代器

  若不想通过迭代器修改目标对象值,定义迭代器常量

  例子:

    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 = 8;
const int lower_bound = 10;
const int upper_bound = 99;

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 = 0; i < size; ++i)
    {
        a[i] = GenerateRandomNumber(10, 99);
    }
    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 0;
}
怕什么真理无穷,进一寸有一寸的欢喜。---胡适
原文地址:https://www.cnblogs.com/hujianglang/p/6260405.html