STL---容器入门1

 1.容器的概念:

概念:用来管理一组元素

首先理解一下数据结构:数据结构研究节点与节点之间关系(主要分为:集合(节点与节点之间是独立的),数组(1:1),链表、树(一对多),图(多对多)

1.1 vector:j就是数组的容器

1.2 Deque(pop ,push)

1.3 list(双向链表)

1.4Set(集合不能放两个相同的数)Mulset (可以存放两个相同的数)

1.5 map(Key-value)

容器类型分类

#include <QCoreApplication>
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
using  namespace std;
/*
 * 学习时间:2019-4-6
 * 学习内容:STL:非常重要
 * STL:六大组件:容器,算法,迭代器,仿函数,适配器,空间配置器
 * STL:将算法与数据结构进行分离
*/
/**
 *1.迭代器
 *2.算法
 *
 */
class Teacher
{
  public :
    int age;
    char name[64];


};
/*容器中装对象*/
void Object_vector()
{
 Teacher t1,t2,t3;
 t1.age=19;
 t2.age=12;
 t3.age=13;
 vector<Teacher> v1;//容器:把你的元素copy to  the vector
 v1.push_back(t1);
 v1.push_back(t2);
 v1.push_back(t3);
 cout<<"traverse  the vector"<<endl;
 for(vector<Teacher>::iterator it=v1.begin(); it!=v1.end();it++)
 {
   cout<<it->age<<endl;
 }
}
void ele_vector()
{
    
    vector<int> v2;//定义v1 为整型的vector
   // v1.push_front(-1);
    v2.push_back(1);
    v2.push_back(2);
    v2.push_back(3);
    v2.push_back(3);
  
    //利用迭代器访问容器
    //迭代相当于一个指针
    for(vector<int >::iterator it=v2.begin();it!=v2.end();it++)
    {
       cout<<*it<<endl;
    }
    //算法 --查找3的个数
    int  num1=count(v2.begin(),v2.end(),3);
     cout<<"the numeber of 3 :"<<num1<<endl;
}
/*容器中装指针*/
void   pointer_vector()
{
    Teacher t1,t2,t3;
    Teacher *p1,*p2,*p3;
    vector<Teacher *> v1; //定义一个指针
    t1.age=12;
    t2.age=13;
    t3.age=14;
    p1=&t1;
    p2=&t2;
    p3=&t3;
    //define pointer variable value
    //把t1,t2,t3,内存首地址放到了容器当中去
    v1.push_back(p1);
    v1.push_back(p2);
    v1.push_back(p3);
    //traverse the vector
    for(vector<Teacher *>::iterator it=v1.begin();it!=v1.end();it++)
    {
        cout<<(*it)->age<<endl;
    }
}
int main()
{
  //对象容器
  cout<<"对象容器"<<endl;
   Object_vector();
  //指针容器
  cout<<"指针容器"<<endl;
   pointer_vector();
   return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42145502/article/details/89061593