c++提高编程 2. STL初识

时间:2021-06-16 18:03:26   收藏:0   阅读:0

了解STL中容器、算法、迭代器概念后,我们利用代码感受STL的魅力

STL中最常用的容器就是Vector,我们可以理解为数组,下面我们将学习如何向这个容器中插入数据、并遍历这个容器

2.5.1 vector存放内置数据类型

容器 vector 

算法 for_each

迭代器 vector<int>::iterator

示例:

#include <iostream>
#include <algorithm>//标准算法库
#include <vector>
using namespace std;

void MyPrint(int val)
{
    cout << val << endl;
}


void test01()
{
    //创建了一个vector容器,数组
    vector<int> v;
    //向容器中插入数据
    v.push_back(10);
    v.push_back(20);
    v.push_back(30);
    v.push_back(40); 
    //通过迭代器访问容器的数据
    //vector<int>::iterator itBeagin = v.begin();//起始迭代器 指向容器中第一个中元素
    //vector<int>::iterator itEnd = v.end();//结束迭代器 指向容器最后一个元素下一个
    ////第一种遍历方式
    //while (itBeagin != itEnd)
    //{
    //    cout << *itBeagin << endl;
    //    itBeagin++;
    //}

    //第二种遍历方式
   /* for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << *it << endl;
    }*/
    //第三种遍历方  利用  STL提供的遍历算法
    for_each(v.begin(), v.end(), MyPrint);

}
int main()
{
    test01();
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!