zoukankan      html  css  js  c++  java
  • C++ STL标准模板库(vector)

    //vector的使用
    #define _CRT_SECURE_NO_WARNINGS
    #include<iostream>
    #include<vector>
    using namespace std;
    
    /*
    引用头文件   #include<vector>
    
    vector类本身是一个类模板
    
    vector类模板是一个线性顺序结构。相当于数组。它可以像数组一样被操作,由于它的特性我们完全可以将vector 看作动态数组。
    */
    
    class Student{
    public:
        int age;
        char name[30];
    };
    
    void ProtectA(){
        //定义一个int类型的动态数组   数组元素为0
        vector<int> v1;
        //vector类模板重载了[]操作符
        //添加元素
        //v1[0] = 2;   报错: out of range  超出数组范围,
        //这说明:vector<int> 数组类模板定义初始长度为空时,添加元素就会报错
        vector<int> v2(5);
        //v2[5] = 12;  报错: out of range  超出数组范围,
    
        /*
        小结:vector<int> 数组类模板的初始化长度是固定的  不可以动态添加
        */
        for (int i = 0; i <5; i++)
        {
            v2[i]=i+1;
        }
        vector<int> v3(2);
        //vector<int> 数组类模板重载=操作符
        v3 = v2;
        /*
        此时v3的长度变成5,可以认为v3的长度发生变化,数据也发生变化
        */
        //size()获取vector数组的长度
        v2[0] = 100;
        /*
        v2改变对v3没有影响
        */
        int numx = v3.size();
        for (int i = 0; i <5; i++)
        {
            cout << v3[i] << endl;
        }
    
        
    }
    
    void Print(vector<Student> &v){
        int num = v.size();
        for (int i = 0; i < num; i++)
        {
            cout << "学生姓名:" << v[i].name << ";学生年龄是:" << v[i].age << endl;
    
        }
    }
    
    void ProtectB(){
        Student s1,s2,s3;
        s1.age = 12;
        strcpy(s1.name, "小米");
        s2.age = 14;
        strcpy(s2.name, "小红");
        s3.age = 16;
        strcpy(s3.name, "小刚");
        vector<Student> vs(3);
        vs[0] = s1;
        vs[1] = s2;
        vs[2] = s3;
        Print(vs);
    }
    
    void main(){
        ProtectB();
        system("pause");
    }
  • 相关阅读:
    python 函数
    谷歌浏览器安装POSTMAN
    Django提示Unknown database处理方法
    Django 连接Mysql异常处理
    Django输入 中文参数保存异常解决方法
    vscode过滤pyc文件
    Jenkins启动和停止服务
    执行robot framework 的测试用例 命令行pybot使用方式
    Jenkins定时任务
    Jenkins构建Python项目失败
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5666081.html
Copyright © 2011-2022 走看看