容器,算法和迭代器实现的基本思路

直接上代码,一调试,一切就明白:

直接在源文件中实现,源文件的名字随便取:

#include<iostream>
using namespace std;

int mycount(int* start ,int* end, int val)//算法,负责统计某个容器中某个元素出现的个数
{
    int num = 0;
    while (start != end)
    {
        if (*start == val)
        {
            num++;
        }
        start++;
    }
    return num;
}

int main(void)
{
    int arr[] = { 0,7,5,4,9,2,0 };//数组 容器
    int* pBegin = arr;//指向容器中第一个元素的位置
    int* pEnd = &arr[sizeof(arr) / sizeof(int)];
    int num = mycount(pBegin, pEnd, 0);//给算法传迭代器
    cout << "num= " << num << endl;
    system("pause");
    return 0;
}
View Code

 进阶一下:

#include<iostream>
#include<vector>//动态数组,可变数组
#include<algorithm>//容器中算法大多定义在这个头文件中
using namespace std;
void PrintVector(int v)
{
    cout << v<<" ";
}

//STL基本语法:
void test01()
{
    vector<int> v;// 定义了一个<容器>,并且指定了容器存放的数据类型是int,这个就是所谓的泛型编程,即利用vector类模板
                  //定义装不同类型元素的vector
    v.push_back(10);//从容器的末尾向容器中逐渐推入元素
    v.push_back(20);
    v.push_back(30);
    v.push_back(40);

    //通过STL提供的for_each 算法遍历容器
    //容器提供迭代器
    vector<int>::iterator pBegin = v.begin();//<迭代器>
    vector<int>::iterator pEnd = v.end();//<迭代器>
    for_each(pBegin, pEnd, PrintVector);//<算法>,for_each算法在<algorithm>这个头文件里面
}
//容器也可以存放自定义的数据类型:
class Person
{
public:
    Person(int age,int id):age(age),id(id){ cout << "构造  函数被调用!!!" << endl; }
    ~Person() { cout << "析构  函数被调用!!!" << endl; }

public:
    int age;
    int id;
};
void test02()
{
    //创建容器,并指定容器元素的类型是Person
    vector<Person> v;
    Person p1(10, 20), p2(30, 40), p3(50, 60);
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);
    //自己写一个遍历容器的算法:
    for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)//it是定义的迭代器变量
    {
        cout << (*it).age << " " << (*it).id << " " << endl;
    }
}
void PrintVector1(Person v)
{
    cout << v.age << " " << v.id << endl;
}
//容器中存放Person类型指针,并且用for_each算法进行元素打印
void test03()
{
    //创建容器,并指定容器元素的类型是Person
    vector<Person> v;
    Person p1(10, 123), p2(30, 124), p3(50, 125);
    Person* per1;
    Person* per2;
    Person* per3;
    per1 = &p1;
    per2 = &p2;
    per3 = &p3;

    v.push_back(*per1);
    v.push_back(*per2);
    v.push_back(*per3);
    //遍历:
    vector<Person>::iterator pBegin = v.begin();//<迭代器>,迭代器说白了就是指针,移动的指针
    vector<Person>::iterator pEnd = v.end();//<迭代器>
    for_each(pBegin, pEnd, PrintVector1);//<算法>
}
int main(void)
{
    //test01();
    //test02();
    test03();
    cout << endl;
    system("pause");
    return 0;
}
View Code

代码来自:传智播客  黑马程序员  联合出品课程(3-07,3-08,3-09)

原文地址:https://www.cnblogs.com/yibeimingyue/p/10545702.html