2. STL初识

 

 

 

 

 

 

 

 

#include<iostream>
#include<vector>
#include<algorithm> // stl标准算法头文件
using namespace std;

// vector容器存放内置数据类型

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

void test01()
{
    // 创建vector容器,认为是一个数组
    vector<int> v;

    v.push_back(1); //  插入数据
    v.push_back(2);
    v.push_back(3);

    vector<int>::iterator itBegin = v.begin(); // 起始迭代器,指向容器第一个元素
    vector<int>::iterator itEnd = v.end(); // 结束迭代器,指向最后一个元素的下一个位置

    // 第一种遍历方式
    /*while (itBegin != itEnd)
    {
        cout << *itBegin << endl;
        itBegin++;
    }
*/
    // 第二种遍历
    //for (auto it = v.begin(); it != v.end(); it++)
    //{
    //    cout << *it << endl;
    //}

    // 第三种遍历
    // 利用stl遍历算法
    for_each(v.begin(), v.end(), myPrint); // 利用回调技术,可以查看for_each定义

}

int main()
{    
    test01();
    return 0;
}

 

#include<iostream>
#include<vector>
#include<algorithm> // stl标准算法头文件
using namespace std;

// vector容器存放自定义数据类型
class Person
{
public:
    Person(string name, int age)
    {
        m_Name = name;
        m_Age = age;
    }
    string m_Name;
    int m_Age;
};

void test01()
{
    vector<Person> v;
    Person p1("aaa", 10);
    Person p2("bbb", 20);
    Person p3("ccc", 30);

    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);

    // 遍历
    for (auto it = v.begin(); it != v.end(); it++)
    {
        cout << "姓名:" << (*it).m_Name << endl; // it->m_Name;
        cout << "年龄" << (*it).m_Age << endl;
    }
}

void test02()
{
    vector<Person*> v;
    Person p1("aaa", 10);
    Person p2("bbb", 20);
    Person p3("ccc", 30);

    v.push_back(&p1);
    v.push_back(&p2);
    v.push_back(&p3);

    // 遍历
    for (auto it = v.begin(); it != v.end(); it++)
    {
        cout << "姓名:" << (*(*it)).m_Name << endl; // it->m_Name;
        cout << "年龄" << (*(*it)).m_Age << endl;
    }
}

int main()
{    
    test02();
    return 0;
}

 

其实类似于二维数组

#include<iostream>
#include<vector>
#include<algorithm> // stl标准算法头文件
using namespace std;

// vector容器嵌套容器

void test01()
{
    vector<vector<int>> v;
    // (*it)就看尖括号里是什么就是什么东西

    vector<int> v1;
    vector<int> v2;
    vector<int> v3;
    vector<int> v4;

    for (int i = 0; i < 4; i++)
    {
        v1.push_back(i*1);
        v2.push_back(i*2);
        v3.push_back(i*3);
        v4.push_back(i*4);
    }
    v.push_back(v1);
    v.push_back(v2);
    v.push_back(v3);
    v.push_back(v4);


    for (auto it = v.begin(); it != v.end(); it++)
    {
        // *it 是一个容器
        for (auto vit = (*it).begin(); vit != (*it).end(); vit++)
        {
            cout << *vit << " ";
        }
        cout << endl;
    }


}
int main()
{    
    test01();
    return 0;
}

 

posted @ 2021-01-18 15:45  不妨不妨,来日方长  阅读(44)  评论(0编辑  收藏  举报