• C++学习笔记34:泛型编程拓展3


    输入流迭代器

    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v(4);
        vector<int>::iterator it = v.begin();
        cout << "enter four ints separated by space & a char:
    ";
        istream_iterator<int> head(cin), tail;
        copy(head, tail, it);
        cin.clear();
        cout << "vector=";
        for ( it = v.begin(); it != v.end(); it++)
        {
            cout << *it << " ";
        }
        cout << endl;
        return 0;
    }

     表:标准模板库中为双向链表

    表的使用

    • 定义包含Point对象的容器:list<Point> pts(8);
    • 插入:pts.insert(pts.begin(),Point(1,2));
    • 表头插入:pts.push_front(Point(1,2));
    • 插入:pts.insert(pts.end(),Point(1,2));
    • 表尾插入:pts.push_back(Point(1,2));
    • 定义包含Point指针的容器:list<Point*>ppts(8);
    • 插入:ppts.insert(ppts.begin(),new Point(1,2));
    • 插入:ppts.insert(ppts.end(),new Point(1,2));
    • 删除:delete ppts.front();ppts.remove(ppts.front());
    • 判断表是否为空:if(pts.empty()) cout << "Empty!";

    表与迭代器

      迭代器可以和表协同工作,方式与向量相同

      list<int> a(8);

      list<int>::iterator it;

      for( it = a.begin();it != a.end();it++)

        *it = GenerateRandomNumber(10,99);

    表排序

    • 直接使用表的成员函数:a.sort();//默认升序
    • 降序:reverse()
    • 降序:(传入函子)greater_equal<int>()
    • a.sort(greater_equal<int>());
    • 对于自定义对象,需要重载operator <以进行比较

    标准算法

    调用标准模板库的函数

    标准函子

      算术函子

        plus<T>

        minus<T>

        multiplies<T>

        divides<T>

        modulus<T>

        negate<T>

    关系函子

        equal_to<T>

        not_equal_to<T>

        greator<T>

        greator_equal<T>

        less<T>

        less_equal<T>

    逻辑函子

        logical_and<T>

        logical_or<T>

        logical_not<T>

    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    CentOS7.4下载与安装
    Windows 环境下vue+webpack前端开发环境搭建
    PHPSSO通信一直失败。
    TortoiseGit安装和使用的图文教程
    TortoiseGit安装教程
    HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth之完全详解
    linux 安装xamp
    linux的rpm命令
    0和空的判断
    mysql中 case when的使用
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6260551.html
Copyright © 2020-2023  润新知