C++

重学C++系列(三)容器

Posted by YaPi on January 17, 2022

数组

表示一组相同类型的数据。长度从0开始,可以访问指定下标的数据。 不可以超过数组长度。

定义例:

int name[10]

# 可以用{}进行初始化
# {} 不仅仅可以用在数组赋值,也可以用在其他类型赋值
int name[] = {}
# 可以省略 = 号

数组下标原则,从0开始,使用非对称区间。

  1. 此区间是一个非对称区间左闭右开
  2. 左闭(下界),右开(上界)
  3. 取值范围: 上界 - 下界
  4. 如取值范围为空,上界值 = 下界值
  5. 即使取值范围为空,上界值永远不可能小于下界值
二维数组

定义 双大括号 tips: 遍历循环时尽可能要满足 “空间局部性”

  1. 在一个小的时间窗口内,访问的遍历那个地址越近越好,这样执行速度快
  2. 一般来说,需要将最长的循环放最内层,最短的循环放最外层,以减少CPU跨切循环层的次数

Vector

vector是面向对象方式的动态数组

它可以轻松实现动态扩容插入元素

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

int main(){
    vector<int> arr = {1,2,3,4,5,6,7};
    cout << "start capacity()" << arr.capacity() << endl;
    // 查看当前已存储元素个数
    cout << "start size()" << arr.size() << endl;
    // 尾部插入一个元素
    arr.push_back(7);
    // 在中间进行元素插入操作
    arr.insert(--arr.end(),9);
    // 删除指定位置
    arr.erase(arr.end() - 1);
    // 删除最后一个元素
    arr.pop_back();
    // 查看容量
    cout << "end capacity()" << arr.capacity() << endl;
    // 查看当前已存储元素个数
    cout << "end size()" << arr.size() << endl;
    for (int index=0;index < arr.size();++index)
        cout << arr[index] << endl;
    return 0;
}

// 输出
start capacity()7
start size()7
end capacity()14
end size()7
1
2
3
4
5
6
7

字符串

  • 字符串是以空字符(’\0’)结束的字符数组
  • 空字符’\0’自动添加到字符串的内部表示中
  • 在声明字符串变量时,应该为空结束符预留一个额外元素空间
char helloword[9] = {"helloworld"};

// 报错
// 需要预留一个字符的空间存储 '\0'
// 也可以不设置长度
char helloword[] = {"helloworld"};
char实现

引入包的头文件

#include <string.h>;
  • strlen(s); 不包含 ‘\0’

  • strcmp(s1,s2); 相同为0,s1 > s2 返回大于0,否则小于0

  • strcpy(s1,s2); 复制s2到s1

  • strcat(s1,s2); 将字符串s2接到s1后面

  • strchr(s1, ch);查找字符串s1中字符ch第一次出现的位置

  • strstr(s1, s2);查找字符串s1中字符串s2第一次出现的位置

这些函数有其安全版本,推荐使用安全版本

strnlen_s, strcpy_s, strncpy_s, strcat_s

string

string 结合了c ++ 的新特性,使用起来比原始的c风格方法更安全和方便,对性能 要求不是特别高的场景可以使用。

引入头文件

#include <string>

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    string s1 = "hello world";
    string s2 ("hello world2");
    string s3 = string("hello wrold4");

    cout << s1.length() << endl;
    //本质和上述一样
    cout << s1.size() << endl;
    cout << s1.capacity() << endl;

    s1 = "hello", s2 = "world";
    // 字符串比较 == 、!= 、>、 >=、 <、 <=
    cout << (s1 == s2) << endl;
    cout << (s1 >= s2) << endl;

    // 转换成c风格字符串
    const char *c_str1 = s2.c_str();
    cout << strlen(c_str1) << endl;
    return 0;
}

取值:可直接使用’[]’下标取值

赋值:直接使用 = 、+= 等。扩容的时候会进行一个动态的操作。