第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:让编程更高效,不要重复造轮子
🎉 恭喜!
你已经完成了所有进阶教程的学习!现在可以开始实战项目了!
➡️ 实战项目
