当前位置: 首页 > article >正文

C++ day05(模版与容器)

目录

【1】模版 template

1》概念

2》函数模版

3》类模版

【2】容器

1》STL标准模版库

2》容器的概念

3》顺序容器 

1> arrry(C++11)

2> vector

 3> list

4> deque

4》 关联容器

5》迭代器 iterator 


【1】模版 template

1》概念

C++模版可以让类或函数声明一种通用类型,使得函数或类中的某些成员变量或成员变量的参数、返回值在实际上的使用中可以是任何类型。

模版可以让程序员写出与类型无关的代码,是泛型编程的基础。

模版主要分为两种实现方式:

1.函数模版

2.类模版

2》函数模版

#include <iostream>

using namespace std;

// 函数模板
template <class T> //可以是class 也可以是typename
T add(T a,T b)
{
    return a+b;
}

class Dog
{

};

int main()
{
    // 在使用的过程中T可以任何类型
    cout << add(2,3) << endl;
    cout << add(2.2,2.2) << endl;
    cout << add('0','0') << endl;
    // 这套通用算法可能不支持某些类型
    // 错误出现的原因并非不能传参,而是不能计算
    cout << add("aa","aa") << endl; // 错误 const char* 指针不能计算
    Dog d1;
    Dog d2;
    add(d1,d2);//错误,类对象不能计算

    return 0;
}

3》类模版

#include <iostream>

using namespace std;

template <typename T>
class Demo
{
private:
    T value;

public:
    Demo(T value):value(value){}

    T get_value() const
    {
        return value;
    }
};

class MobilePhone
{
private: // 私有:被修饰的成员只能在类内访问
    string brand; // 读写
    string model = "16"; // 只读
    int weight; // 只写

public:
    string get_brand() // getter:读函数
    {
        return brand;
    }

    void set_brand(string b) // setter:写函数
    {
        brand = b;
    }

    string get_model()
    {
        return model;
    }

    void set_weight(int w)
    {
        weight = w;
    }
};

int main()
{
    // 类模板在创建对象时要标注T的具体类型,以便于开辟内存
    Demo<int> d1(1);//T 为 int 类型
    cout << sizeof(d1) << " " << d1.get_value() << endl; // 4 1

    Demo<long> d2(1);//T 为 long 类型
    cout << sizeof(d2) << " " << d2.get_value() << endl; // 4 1

    MobilePhone mp1;
    Demo<MobilePhone> d3(mp1);//T 为 MobilePhone 类型
    cout << sizeof(d3) << endl; // 12

    return 0;
}

类模版声明定义分离时,编写稍微繁琐

#include <iostream>

using namespace std;

template <typename T>
class Demo
{
private:
    T value;

public:
    Demo(T value);
    T get_value() const;
};

template <typename T> //每个函数定义时都需要写上模版的声明
Demo<T>::Demo(T value)
{
    this->value = value;
}

template <typename T>
T Demo<T>::get_value() const
{
    return value;
}

class MobilePhone
{
private: // 私有:被修饰的成员只能在类内访问
    string brand; // 读写
    string model = "16"; // 只读
    int weight; // 只写

public:
    string get_brand() // getter:读函数
    {
        return brand;
    }

    void set_brand(string b) // setter:写函数
    {
        brand = b;
    }

    string get_model()
    {
        return model;
    }

    void set_weight(int w)
    {
        weight = w;
    }
};

int main()
{
    // 类模板在创建对象时要标注T的具体类型,以便于开辟内存
    Demo<int> d1(1);
    cout << sizeof(d1) << " " << d1.get_value() << endl; // 4 1

    Demo<long> d2(1);
    cout << sizeof(d2) << " " << d2.get_value() << endl; // 4 1

    MobilePhone mp1;
    Demo<MobilePhone> d3(mp1);
    cout << sizeof(d3) << endl; // 12

    return 0;
}

【2】容器

1》STL标准模版库

标准模板库(Standard Template Library,STL)是惠普实验室开发的一系列软件的统称。虽说它主要表出现到C++中,但在被引入C++之前该技术就已经存在了很长时间。

STL的代码从广义上讲分为三类:algorithm(算法)、container(容器)和iterator(迭代器),几乎所有的代码都采用了模板类和模板函数的方式,这相比于传统的由函数和类组成的库来说提供了更好的代码重用机会。

2》容器的概念

容器是存储数据的集合,存储的数据元素可以是任何类型,因为容器是模版实现的。容器类对象只能使用栈内存,不支持堆内存。另外,容器类的使用都需要引入对应的头文件。 

3》顺序容器 

顺序容器是一种线性结构的可序群集,但是可以通过或删除(array不支持)等操作改变元素的位置。

1> arrry(C++11)

array比内置数组更加安全和易于使用。

#include <iostream>
#include <array> // 头文件

using namespace std;


int main()
{
    array<int,5> arr; // 创建一个长度为5的int数组
    // 赋值
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;
    // 修改
    arr.at(2) = 222;
    arr[3] = 333;

//    cout << arr.at(-3248673) << endl; 崩溃

    // 遍历输出
    for(int i =0;i<arr.size();i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;

    arr.fill(666); // 更改所有元素的值
    for(int i:arr)
        cout << i << " ";
    cout << endl;

    // 迭代器(略)

    return 0;
}

2> vector

vector 内部通过数组实现,但是vector 是可变长的,因此每次长度变化时,内部重新创建数组,能高效的进行随机存取(数组的内存连续),但是不擅长插入删除。

#include <iostream>
#include <vector> // 头文件

using namespace std;

int main()
{
    vector<int> vec1; // 创建一个长度为0的对象
    cout << vec1.empty() << endl; // 1

    vector<int> vec2(5); // 创建一个长度为5的对象
    for(int i=0;i<vec2.size();i++)
        cout << vec2.at(i) << " "; // 0 0 0 0 0

    cout << endl;

    vector<int> vec3(vec2); // 拷贝构造
    for(int i:vec3)
        cout << i << " ";

    cout << endl;

    // 参数1:长度
    // 参数2:默认值
    vector<string> vec4(5,"AAA");
    // 增加元素
    vec4.push_back("BBB"); // 尾插
    // 在第二个位置插入元素
    // begin返回一个迭代器指针,指向第一个元素
    vec4.insert(vec4.begin()+1,"No.2");
    // 在倒数第三个位置插入元素
    // end返回一个迭代器指针,指向最后一个元素的后面
    vec4.insert(vec4.end()-2,"No.-3");

    // 删除数据
    vec4.pop_back(); // 删除最后一个数据
    // 删除第一个数据
    vec4.erase(vec4.begin());
    // 删除倒数第一个数据
    vec4.erase(vec4.end()-1);

    // 删除所有元素
    vec4.clear();

    for(string i:vec4)
        cout << i << " ";
    cout << endl;

    // 迭代器(略)

    return 0;
}

 3> list

list 内部由双向链表实现,内存空间不连续,只能通过迭代器指针访问,不支持下标,但是可以高效的进行插入删除操作,不擅长随机存取。

#include <iostream>
#include <list> // 头文件

using namespace std;

int main()
{
    list<int> lis1; // 创建一个长度为0的对象
    cout << lis1.empty() << endl; // 1

    list<int> lis2(5); // 创建一个长度为5的对象

    cout << endl;

    list<int> lis3(lis2); // 拷贝构造
    for(int i:lis3)
        cout << i << " ";

    cout << endl;

    // 参数1:长度
    // 参数2:默认值
    list<string> lis4(5,"AAA");
    // 增加元素
    lis4.push_back("BBB"); // 尾插
    // 在第二个位置插入元素
    // begin返回一个迭代器指针,指向第一个元素
    lis4.insert(++lis4.begin(),"No.2");
    // 在倒数第三个位置插入元素
    // 存储迭代器指针
    list<string>::iterator iter =  lis4.end();
    // 移动迭代器指针,-2表示向前移动两位
    advance(iter,-2);
    // end返回一个迭代器指针,指向最后一个元素的后面
    lis4.insert(iter,"No.-3");

    // 删除数据
    lis4.pop_back(); // 删除最后一个数据
    // 删除第一个数据
    lis4.erase(lis4.begin());
    // 删除倒数第一个数据
    lis4.erase(--lis4.end());

    // 删除所有元素
//    lis4.clear();

    // 头插
    lis4.push_front("头");
    // 删除第一个元素
    lis4.pop_front();
    // 取出第一个和最后一个元素的引用
    cout << lis4.front() << " " << lis4.back() << endl;

    // 排序(升序)
    lis4.sort();

    for(string i:lis4)
        cout << i << " ";
    cout << endl;

    // 迭代器(略)

    return 0;
}

4> deque

插入删除和随机存取的性能介于 vector 和 list 之间,擅长两端存取,API几乎兼容 vector 和 list。

4》 关联容器

各个元素之间没有严格的顺序关系,但是内部仍然有排序的热点,因此才可以使用迭代器进行遍历。

最常用的关联容器是 map :键值对映射。

 

键(Key)的功能是元素名称,因此常用字符串表示,且具备唯一性;值可以是任何类型,且值可以重复。

#include <iostream>
#include <map> // 头文件

using namespace std;

int main()
{
    map<string,int> ma;
    cout << ma.empty() << endl; // 1
    // 插入数据
    ma["height"] = 180;
    ma["salary"] = 17999;
    ma["salary"] = 18000; // 因为之前有这个键了,变为修改
    ma.insert(pair<string,int>("age",28));
    ma.insert(pair<string,int>("weight",78));
    ma.insert(pair<string,int>("weight",79)); // 之前有此键,不改
    ma["comm"] = 2000;

    cout << ma.size() << endl; // 5

    // 取出元素
    cout << ma["weight"] << endl; // 78
    cout << ma["salary"] << endl; // 18000

    // 判断一个元素是否存在
    map<string,int>::iterator iter =  ma.find("name"); // 拿到迭代器指针
    if(iter == ma.end()) // 没有此键
    {
        cout << "没有name键" << endl;
    }

    // 删除一个元素
    // 返回值表示删除结果
    // ==0:删除失败  >0:删除成功
    int result = ma.erase("age");
    if(result)
    {
        cout << "删除成功" << endl;
    }else
    {
        cout << "删除失败" << endl;
    }

    result = ma.erase("age");
    if(result)
    {
        cout << "删除成功" << endl;
    }else
    {
        cout << "删除失败" << endl;
    }

    ma.clear();
    cout << ma.size() << endl; // 0

    return 0;
}

5》迭代器 iterator 

迭代器是一种特殊的指针,可以遍历所有的容器,常用的迭代器有:

1.iterator  读写迭代器

2.const_iterator 只读迭代器

#include <iostream>
#include <array>
#include <vector>
#include <list>
#include <deque>
#include <map>

using namespace std;

int main()
{
    string s = "fklsdhfjksdhfjksdhjk";

    array<double,5> arr;
    vector<int> vec(5);
    list<int> lis(5);
    deque<int> deq(5);
    for(int i=0;i<arr.size();i++)
    {
        deq[i] = vec[i] = arr[i] = i+1;
        lis.push_back(i+1);
    }

    map<string,int> ma;
    // 插入数据
    ma["height"] = 180;
    ma["salary"] = 18000;
    ma.insert(pair<string,int>("age",28));
    ma.insert(pair<string,int>("weight",78));
    ma["comm"] = 2000;

    // 开始迭代器!
    for(string::const_iterator iter = s.begin();
        iter != s.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;

    for(array<double,5>::iterator iter = arr.begin();
        iter != arr.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;

    for(vector<int>::iterator iter = vec.begin();
        iter!= vec.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;

    for(list<int>::iterator iter = lis.begin();
        iter!= lis.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;

    for(deque<int>::iterator iter = deq.begin();
        iter!= deq.end();iter++)
    {
        cout << *iter << " ";
    }
    cout << endl;

    for(map<string,int>::iterator iter = ma.begin();
        iter!=ma.end();iter++)
    {
        //  通过first和second区分键值
        cout << iter->first << " " << iter->second << endl;
    }

    return 0;
}

今天的分享就到这里结束啦,如果有哪里写的不好的地方,请指正。
如果觉得不错并且对你有帮助的话点个关注支持一下吧!


http://www.kler.cn/news/341070.html

相关文章:

  • MySQL高阶2010-职员招聘人数2
  • 前端Javascript常见算法题(一)【待学】
  • Android SELinux——基础介绍(一)
  • 机器学习周报(9.30-10.6)
  • PCL 3D-SIFT关键点检测(曲率不变特征约束
  • 系统架构设计师教程 第12章 12.4 信息系统架构案例分析 笔记
  • 激光增材制造新突破:精细调控NiTi合金弹热效应,实现制冷定制
  • 自动化测试selenium篇(三)
  • PMP--冲刺题--解题--1-10
  • 中阳:引领未来投资的创新金融平台
  • MySQL 篇-深入了解存储引擎、索引(InnoDB 索引结构 B+Tree、索引使用规则)
  • golang接口详解
  • x-cmd pkg | zellij - 终端复用器,能作为 tmux 的替代品
  • LVGL仪表盘逆时针
  • IDEA之手动添加作者信息
  • 『网络游戏』服务器使用PESorket【13】
  • 使用HttpsClient来idea发送请求
  • Android targetSdkVersion 升级为34 问题处理
  • 减少重复的请求之promise缓存池(闭包版) —— 缓存promise,多次promise等待并返回第一个promise的结果
  • 75.【C语言】文件操作(2)