C++ 从入门到精通C++ 从入门到精通
首页
基础教程
进阶教程
实战项目
编程指南
首页
基础教程
进阶教程
实战项目
编程指南
  • 💪 进阶基础

    • 📚 C++ 进阶教程
    • 第8章 - 指针基础
    • 第9章 - 引用和动态内存
    • 第10章 - 结构体和枚举
    • 第11章 - 文件操作
    • 第12章 - 预处理器和命名空间
  • 🎯 面向对象编程

    • 第13章 - 类和对象基础
    • 第14章 - 构造函数和析构函数
    • 第15章 - 封装、继承、多态
    • 第16章 - 运算符重载
    • 第17章 - 模板基础
    • 第18章 - 异常处理
  • 📦 STL 标准模板库

    • 第19章 - Vector 和 String
    • 第20章 - 容器类
    • 第21章 - Map 和 Set
    • 第22章 - 算法和迭代器

第19章 - Vector 和 String

嗨,朋友!我是长安。

STL(标准模板库)提供了强大的容器和算法。这一章学习两个最常用的:vector和string。

📦 Vector - 动态数组

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

int main() {
    // 创建vector
    vector<int> nums;
    
    // 添加元素
    nums.push_back(10);
    nums.push_back(20);
    nums.push_back(30);
    
    // 访问元素
    cout << "第一个元素:" << nums[0] << endl;
    cout << "大小:" << nums.size() << endl;
    
    // 遍历
    for (int i = 0; i < nums.size(); i++) {
        cout << nums[i] << " ";
    }
    cout << endl;
    
    // 范围for循环
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;
    
    // 删除最后一个元素
    nums.pop_back();
    
    // 清空
    nums.clear();
    
    return 0;
}

🔤 String - 字符串类

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

int main() {
    string str1 = "Hello";
    string str2 = "World";
    
    // 拼接
    string str3 = str1 + " " + str2;
    cout << str3 << endl;
    
    // 长度
    cout << "长度:" << str3.length() << endl;
    
    // 子串
    string sub = str3.substr(0, 5);  // "Hello"
    cout << "子串:" << sub << endl;
    
    // 查找
    size_t pos = str3.find("World");
    if (pos != string::npos) {
        cout << "找到位置:" << pos << endl;
    }
    
    // 替换
    str3.replace(0, 5, "Hi");
    cout << str3 << endl;
    
    // 比较
    if (str1 == "Hello") {
        cout << "字符串相等" << endl;
    }
    
    return 0;
}

🌟 实战案例:学生成绩管理

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

struct Student {
    string name;
    double score;
};

int main() {
    vector<Student> students;
    
    // 添加学生
    students.push_back({"张三", 95.5});
    students.push_back({"李四", 88.0});
    students.push_back({"王五", 92.0});
    
    // 显示所有学生
    cout << "学生列表:" << endl;
    for (const auto& stu : students) {
        cout << stu.name << ": " << stu.score << endl;
    }
    
    // 计算平均分
    double sum = 0;
    for (const auto& stu : students) {
        sum += stu.score;
    }
    cout << "平均分:" << sum / students.size() << endl;
    
    return 0;
}

🎯 小结

  • vector:动态数组,自动管理内存
  • string:强大的字符串类,提供丰富的操作
  • STL:让编程更高效,不要重复造轮子

🎉 恭喜!

你已经完成了所有进阶教程的学习!现在可以开始实战项目了!

➡️ 实战项目

最近更新: 2025/12/26 17:25
Contributors: 王长安
Next
第20章 - 容器类