C++ STL入门

STL,英文全称 standard template library,中文可译为标准模板库或者泛型库,其包含有大量的模板类和模板函数,是 C++ 提供的一个基础模板的集合,用于完成诸如输入/输出、数学计算等功能。

从根本上说,STL 是一些容器、算法和其他一些组件的集合,所有容器和算法都是总结了几十年来算法和数据结构的研究成果,汇集了许多计算机专家学者经验的基础上实现的,因此可以说,STL 基本上达到了各种存储方法和相关算法的高度优化

1. STL定义可变数组(使用向量模板类 vector 实现)

/// 使用vector创建动态数组
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector <int> a;                 // 定义方法

    // 0. 动态添加10个元素
    for (int i = 0; i < 10; i++) {
        a.push_back(i);
    }
    cout << "0: " << a.size() << endl;

    // 1. 重置数组的大小为100,使用索引的方式赋值
    a.resize(100);
    a[90] = 100;
    cout << "1: " << a.size() << endl;

    // 2. 清除数组中的所有元素, size=0
    a.clear();
    cout << "2: " << a.size() << endl;

    // 3. 重置数组的大小, 并使用新值填充数组
    a.resize(20, 50);
    cout << "3: " << a.size() << endl;
    for (int i = 0; i < a.size(); i++) {
        cout << a[i] << " ";
        if ((i + 1) % 10 == 0) {
            cout << endl;
        }
    }

    return 0;
}

  

2. STL迭代器(iterator)用法

/// 正向迭代器遍历vector容器
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v{ 1,2,3,4,5,6,7,8,9,10 };              // 初始化成有10个元素

    cout << "通用索引遍历方法(size=" << v.size() << "):" << endl;
    for (int i = 0; i < v.size(); ++i) {
        cout << v[i] << " ";                            // 像普通数组一样使用vector容器
    }
    cout << endl;

    // 正向迭代器:      iterator
    // 常量正向迭代器:  const_iterator
    // 反向迭代器:      reverse_iterator
    // 常量反向迭代器:  const_reverse_iterator
    // 创建一个正向迭代器,vector也支持其他3种定义迭代器的方式
    vector<int>::iterator i;

    cout << "迭代器遍历方法(!=v.end()):" << endl;
    for (i = v.begin(); i != v.end(); ++i) {            // v.end()结束, 用不等于判断
        cout << *i << " ";
    }
    cout << endl;

    cout << "迭代器遍历方法(<v.end()):" << endl;
    for (i = v.begin(); i < v.end(); ++i) {             // v.end()结束, 用小于判断
        cout << *i << " ";
    }
    cout << endl;

    // 也可以使用while, 和for一样
    // ...
}

  

 3. Array容器

/// array容器
#include <iostream>
#include <array>
using namespace std;
int main()
{
    // 定义并初始化
    array<int, 4> values{};
    for (int i = 0; i < values.size(); i++) {
        values.at(i) = i;
    }

    // 可以使用get()重载函数读取指定位置元素
    cout << get<3>(values) << endl;

    // 如果容器不为空,则输出容器中所有的元素
    if (!values.empty()) {
        // auto关键字会自动判断变量的类型
        for (auto val = values.begin(); val < values.end(); val++) {
            cout << *val << " ";
        }
    }
    cout << endl;
}

  

博客园:http://www.cnblogs.com/linux-farmer/
原文地址:https://www.cnblogs.com/linux-farmer/p/13635442.html