c++ STL vector容器(int类型、自定义对象类型、嵌套容器)for_each回调函数打印

容器:能放下元素
序列容器:元素的位置是进入容器的时间和地点决定
关联容器:容器规定好了,比如大的在前,小的在后

迭代器:可以理解为指针,用*能拿到元素,也能++,但迭代器其实是一个类?这个类封装了一个指针。
默认指向第一个位置.

算法:步骤有限,哪怕加法也是。查找、排序等。STL大约实现100个算法的函数。
写容器的提供迭代器,写算法的用迭代器。
迭代器开始和结束标志指针,begin、end都要提供  

用到哪个容器,就导入哪个容器的头文件。

一般都有插入、删除、查找功能。


#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

//传入for_each的回调函数
void printInt(int v)
{
    cout<<v<<'\t';
}

//vector<int>类型的迭代器
void testInt()
{
    vector<int> v;
    //放元素
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    //开始和结束的迭代器
    vector<int>::iterator begin = v.begin();
    vector<int>::iterator end = v.end();
    for_each(begin,end,printInt);
    cout<<endl;
}

//自建类型Person
class Person
{
public:
    Person(){}
    Person(int id,int age):age(age),id(id){}
    void detail()
    {   
        cout<<"id: "<<this->id<<" age: "<<this->age<<endl;
    }
private:
    int age;
    int id;
};

//自定义的Person类型放入容器
void testPerson()
{
    Person p1(1,10);
    Person p2(2,20);
    vector<Person> v;
    v.push_back(p1);
    v.push_back(p2);

    //使用迭代器的循环方式
    for(vector<Person>::iterator begin = v.begin();begin!=v.end();begin++)
    {
        //可能是迭代器重载了*号,因此可以用这个得到对象
        (*begin).detail();
    }
}

//嵌套容器的回调打印函数
//这里假设是容器里面嵌套了int容器
void printNesting(vector<int> v)
{
    //这些都是前面现成的
    vector<int>::iterator begin = v.begin();
    vector<int>::iterator end = v.end();
    for_each(begin,end,printInt);
}

typedef vector<int>(VECTOR);
//嵌套容器
void testNesting()
{
    //定义一个数组容器的容器
    //vector<VECTOR> v_nest;  //这个可以
    vector<vector<int> > v_nest;
    vector<int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);
    v1.push_back(4);
    vector<int> v2;
    v2.push_back(11);
    v2.push_back(22);
    v2.push_back(32);
    v2.push_back(42);
    v_nest.push_back(v1);
    v_nest.push_back(v2);
    vector<VECTOR>::iterator begin = v_nest.begin();
    vector<VECTOR>::iterator end = v_nest.end();
    for_each(begin,end,printNesting);
    
}


int main()
{
    //testInt();
    //testPerson();
    testNesting();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hiudawn/article/details/80038799
今日推荐