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

本文介绍如何使用C++标准模板库(STL)中的find函数进行数组和向量中元素的查找,并展示了不同类型的迭代器应用实例,包括向量迭代器、常迭代器及流迭代器的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

调用标准模板库的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值