c++数组详细介绍(二)

简介: c++数组详细介绍(二)

c++数组详细介绍(一)https://developer.aliyun.com/article/1437023

7. 标准模板库(STL):

a. std::vector:

std::vector 是一个动态数组,可以在运行时动态改变其大小。它提供了许多方便的方法来操作元素,如添加、删除、访问等。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 6};

    // 遍历vector
    for (int element : vec) {
        std::cout << element << " ";
    }
    std::cout << std::endl;

    // 添加元素
    vec.push_back(10);

    // 使用迭代器遍历vector
    std::cout << "After adding an element: ";
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

b. std::array:

std::array 是一个固定大小的数组,与传统数组相似但提供了更多的功能和安全性。

#include <array>

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};

    // 遍历array
    for (int element : arr) {
        std::cout << element << " ";
    }
    std::cout << std::endl;

    // 访问元素
    int value = arr[2];
    std::cout << "Element at index 2: " << value << std::endl;

    return 0;
}


c. STL算法:

STL提供了许多算法,可以直接应用于数组、向量等容器。以下是一些示例:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 6};

    // 使用STL算法对vector进行排序
    std::sort(vec.begin(), vec.end());

    // 使用STL算法查找元素
    int target = 6;
    auto result = std::find(vec.begin(), vec.end(), target);

    if (result != vec.end()) {
        std::cout << "Element found at position: " << std::distance(vec.begin(), result) << std::endl;
    } else {
        std::cout << "Element not found" << std::endl;
    }

    return 0;
}


8. 异常处理:

a. 数组越界:

数组越界是指尝试访问数组中不存在的索引位置。这可能导致未定义的行为,例如访问不属于数组的内存区域,可能导致程序崩溃。

#include <stdexcept>

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};

    try {
        // 错误的数组越界访问
        int value = myArray[10];  // 这会导致未定义的行为
        std::cout << "Value at index 10: " << value << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}


b. 使用std::vector和迭代器:

使用std::vector和迭代器可以提高代码的安全性,因为它们提供了动态调整大小的能力,且迭代器会自动确保不越界。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    try {
        // 安全的访问vector元素
        int value = vec.at(10);  // 这会抛出std::out_of_range异常
        std::cout << "Value at index 10: " << value << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}


c. 自定义异常:

有时,可以根据具体的应用场景自定义异常类,以便更好地捕获和处理特定类型的错误。

#include <iostream>
#include <stdexcept>

class ArrayIndexException : public std::runtime_error {
public:
    ArrayIndexException(const std::string& message)
        : std::runtime_error(message) {}
};

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};

    try {
        // 错误的数组越界访问
        int index = 10;
        if (index < 0 || index >= 5) {
            throw ArrayIndexException("Array index out of bounds");
        }
        int value = myArray[index];
        std::cout << "Value at index " << index << ": " << value << std::endl;
    } catch (const ArrayIndexException& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

d. 示例:

以下是一个完整的示例,演示了如何处理数组越界异常:

#include <iostream>
#include <stdexcept>

class ArrayIndexException : public std::runtime_error {
public:
    ArrayIndexException(const std::string& message)
        : std::runtime_error(message) {}
};

int main() {
    int myArray[5] = {1, 2, 3, 4, 5};

    try {
        // 错误的数组越界访问
        int index = 10;
        if (index < 0 || index >= 5) {
            throw ArrayIndexException("Array index out of bounds");
        }
        int value = myArray[index];
        std::cout << "Value at index " << index << ": " << value << std::endl;
    } catch (const ArrayIndexException& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

9. 动态数组:

a. 动态分配内存:

在C++中,可以使用new关键字动态分配内存,用于创建动态数组。动态分配的数组的大小可以在运行时确定。

#include <iostream>

int main() {
    // 动态分配一个整数数组
    int* dynamicArray = new int[5];

    // 初始化动态数组
    for (int i = 0; i < 5; ++i) {
        dynamicArray[i] = i + 1;
    }

    // 使用动态数组
    for (int i = 0; i < 5; ++i) {
        std::cout << dynamicArray[i] << " ";
    }
    std::cout << std::endl;

    // 释放动态分配的内存
    delete[] dynamicArray;

    return 0;
}

b. 动态数组的释放:

动态分配的数组在使用完毕后,应使用delete[]关键字释放相应的内存,以防止内存泄漏。

int* dynamicArray = new int[5];

// 使用动态数组

// 释放动态分配的内存
delete[] dynamicArray;

c. 动态数组和指针:

动态数组是通过指针来管理的,因此使用指针的概念来访问和操作动态数组。

int* dynamicArray = new int[5];

// 使用指针访问动态数组元素
int value = dynamicArray[2];

// 释放动态分配的内存
delete[] dynamicArray;

d. 注意事项:

必须使用 delete[] 来释放通过 new[] 分配的数组内存。

确保在使用完动态数组后释放内存,以防止内存泄漏。

避免采用不安全的指针操作,以免导致悬挂指针等问题。


e. 示例:

以下是一个完整的示例,演示了如何动态分配和释放内存以创建动态数组:

#include <iostream>

int main() {
    // 动态分配一个整数数组
    int* dynamicArray = new int[5];

    // 初始化动态数组
    for (int i = 0; i < 5; ++i) {
        dynamicArray[i] = i + 1;
    }

    // 使用动态数组
    std::cout << "Dynamic Array: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << dynamicArray[i] << " ";
    }
    std::cout << std::endl;

    // 释放动态分配的内存
    delete[] dynamicArray;

    return 0;
}

10. 字符串(String)与字符数组(Char Array):

a. 字符数组的声明和初始化:

字符数组是一种存储字符序列的数据结构,以null字符 \0 结尾。

char charArray[] = "Hello";


b. 字符串类 std::string:

std::string 是C++标准库中提供的字符串类,它提供了许多方便的方法来处理字符串。

#include <iostream>
#include <string>

int main() {
    // 使用字符串类
    std::string str = "Hello, C++";

    // 输出字符串
    std::cout << "String: " << str << std::endl;

    // 获取字符串长度
    std::cout << "Length: " << str.length() << std::endl;

    // 字符串连接
    std::string newStr = str + " Programming";
    std::cout << "Concatenated String: " << newStr << std::endl;

    return 0;
}


c. 字符数组与字符串类的转换:

可以使用字符串类的成员函数 c_str() 将字符串类转换为字符数组。

#include <iostream>
#include <string>

int main() {
    // 字符数组转字符串类
    char charArray[] = "Hello, C++";
    std::string strFromCharArray(charArray);

    // 输出字符串类
    std::cout << "String from Char Array: " << strFromCharArray << std::endl;

    // 字符串类转字符数组
    const char* charPtr = strFromCharArray.c_str();

    // 输出字符数组
    std::cout << "Char Array from String: " << charPtr << std::endl;

    return 0;
}


d. 常用字符串操作

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, C++";

    // 获取字符串长度
    std::cout << "Length: " << str.length() << std::endl;

    // 字符串比较
    std::string otherStr = "Hello, C++";
    if (str == otherStr) {
        std::cout << "Strings are equal" << std::endl;
    } else {
        std::cout << "Strings are not equal" << std::endl;
    }

    // 查找子串
    size_t pos = str.find("C++");
    if (pos != std::string::npos) {
        std::cout << "Found at position: " << pos << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }

    return 0;
}


e. 示例:

以下是一个完整的示例,演示了字符数组和字符串类的基本操作:

#include <iostream>
#include <string>

int main() {
    // 字符数组转字符串类
    char charArray[] = "Hello, C++";
    std::string strFromCharArray(charArray);

    // 输出字符串类
    std::cout << "String from Char Array: " << strFromCharArray << std::endl;

    // 字符串类转字符数组
    const char* charPtr = strFromCharArray.c_str();

    // 输出字符数组
    std::cout << "Char Array from String: " << charPtr << std::endl;

    // 使用字符串类进行操作
    std::string str = "Hello, C++";
    std::cout << "Length: " << str.length() << std::endl;

    std::string otherStr = "Hello, C++";
    if (str == otherStr) {
        std::cout << "Strings are equal" << std::endl;
    } else {
        std::cout << "Strings are not equal" << std::endl;
    }

    size_t pos = str.find("C++");
    if (pos != std::string::npos) {
        std::cout << "Found at position: " << pos << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }

    return 0;
}



目录
相关文章
|
2月前
|
存储 算法 编译器
【C++ 字符数组的模板特化】面向字符串的C++模板特化:理解与实践
【C++ 字符数组的模板特化】面向字符串的C++模板特化:理解与实践
48 1
|
2月前
|
存储 缓存 安全
C++数组全解析:从基础知识到高级应用,领略数组的魅力与技巧
C++数组全解析:从基础知识到高级应用,领略数组的魅力与技巧
54 1
|
2月前
|
存储 算法 搜索推荐
在C++编程语言中数组的作用类型
在C++编程语言中数组的作用类型
14 0
在C++编程语言中数组的作用类型
|
2月前
|
C++
.C++中结构体数组docx
.C++中结构体数组docx
14 0
|
3月前
|
人工智能 移动开发 算法
【动态规划】【C++算法】LeetCoce996正方形数组的数目
【动态规划】【C++算法】LeetCoce996正方形数组的数目
|
2天前
|
存储 C++
【C++模板】模板实现通用的数组
【C++模板】模板实现通用的数组
|
7天前
|
存储 人工智能 C++
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
【重学C++】【指针】详解让人迷茫的指针数组和数组指针
28 1
|
20天前
|
C++ 索引
C++ 获取数组大小、多维数组操作详解
本文介绍了如何获取数组的大小和使用`sizeof()`运算符。`sizeof()`返回数组所占字节数,而非元素个数。要获取元素个数,需除以单个元素的大小。此外,文章展示了如何使用`sizeof()`遍历数组,包括多维数组。多维数组是数组的数组,可用来表示网格。文中以战舰游戏为例说明了多维数组的应用。最后提到了微信公众号`Let us Coding`以获取更多内容。
22 0
|
22天前
|
存储 C++ 索引
C++数组
C++数组
|
23天前
|
C++
C++语言学习数组和字符串应用案例
【4月更文挑战第8天】该文展示了C++中数组和字符串的应用案例。数组示例定义了一个整数数组并访问、修改其元素,计算了元素之和。字符串示例中,定义了一个字符串并遍历、修改字符,进行了字符串拼接、查找子字符串及替换操作。
10 3