STL编程概述(一)

 STL是一个C++通用库,它主要又迭代器(iterators)、算法(algorithms)、容器(containers)、函数对象(function object)、内存分配器( allocators)和适配器(adapter)等六大部分组成。

 STL 是标准化的组件,对于编程人员来说,标准化组件以为着可以直接使用这些现成的组件,而不用重新开发。STL现在是C++的一部分,因此不用额外安装,它被内建在编译器之内。使用STL最重要的就是掌握基本理论和编程方法,从而能够举一反三,下面通过对比来阐述STL的基本概念。

在传统的C++中,一般习惯使用数组和指针来进行数据的管理和分配,例子如下:

#include <cstdlib>
#include <iostream>
using namespace std;

int cmp ( const void *a , const void *b)
{
    int aa = *(int *)a;
    int bb = *(int *)b;
    return (aa < bb) ? -1 : (aa > bb) ? 1 : 0;
}

int main (int argc , char *argcv[])
{
    const int size = 10;
    int array [size];
    int n = 0;
    cout << "please input 10 integers:" << endl;
    while (cin >> array[n++] && (n <= (size - 1)));
    qsort (array, n, sizeof(int), cmp);
    cout << "output the 10 sorted integers:" << endl;
    for (int i = 0; i < size; ++i)
    {
        cout << array[i] << " ";
    }
}

上述代码的功能在于读取一整数序列并存入数组中,然后对该数组进行排序,最后把排序后的数组打印出来。
容器主要用于包含其他对象的类,就像数组,队列,堆栈等数据结构可以包含整数,小数,类等数据成员一样,最常见的容器模板类就是向量类(vector)。使用向量类和迭代器对上面的代码进行修改。

#include <iostream>
#include <vector>
#include <algorithm>


using namespace std;


int main(int argc, char const *argv[])
{
    vector<int> v;
    int input;
    int n = 0;
    cout << "Please input 10 intergers:" << endl;
    while ((++n) && (n < 11))
    {
        cin >> input;
        v.push_back(input);
    }
    sort (v.begin(), v.end());
    n = v.size();
    cout << "Output the 10 sorted integers:" << endl;
    for (int i = 0; i < n; ++i)
    {
        cout << v[i] << " ";
    }
}

在上面的例子中使用了vector和iterator技术。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值