在C++中,std::string
和 std::vector
是标准模板库(STL)中最常用的两个容器,它们分别用于字符串操作和动态数组管理。以下是对这两个类的详细介绍:
1. std::string
std::string
是 STL 中用于处理和操作字符串的类。它封装了字符数组并提供了丰富的字符串操作功能,相比 C 风格的字符数组(char[]
或 char*
),std::string
更加安全和易用。
主要特性:
- 自动内存管理:无需手动分配和释放内存,
std::string
自动处理内存管理。 - 丰富的成员函数:提供了许多成员函数用于字符串的操作,如拼接、查找、替换、截取等。
- 支持直接赋值和比较:可以直接通过赋值号(
=
)进行赋值,并通过比较操作符(==
,!=
,<
,>
等)进行比较。 - 安全性:
std::string
会在边界检查、内存分配等方面提供更多的保护,避免缓冲区溢出等问题。
常用操作:
#include <iostream>
#include <string>
int main() {
std::string s1 = "Hello";
std::string s2 = "World";
// 拼接
std::string s3 = s1 + " " + s2; // "Hello World"
// 获取字符串长度
std::cout << "Length: " << s3.length() << std::endl; // 11
// 查找子串
std::size_t pos = s3.find("World");
if (pos != std::string::npos) {
std::cout << "'World' found at position: " << pos << std::endl;
}
// 字符串比较
if (s1 < s2) {
std::cout << s1 << " comes before " << s2 << std::endl;
}
// 替换子串
s3.replace(6, 5, "C++"); // "Hello C++"
// 截取子串
std::string sub = s3.substr(6, 3); // "C++"
std::cout << "Final string: " << s3 << std::endl;
return 0;
}
其他重要函数:
append()
,erase()
,insert()
,clear()
,empty()
,at()
,c_str()
(返回 C 风格字符串)
2. std::vector
std::vector
是 STL 中最常用的动态数组容器。与 C 风格数组不同,std::vector
会动态管理内存,允许你在运行时根据需要增加或减少数组的大小。
主要特性:
- 动态大小:
std::vector
可以自动调整其大小,支持动态增长,不需要提前确定大小。 - 连续存储:
std::vector
内部以连续的内存块存储元素,支持快速的随机访问。 - 自动内存管理:类似于
std::string
,std::vector
会自动管理内存,不需要手动分配和释放。 - 灵活的插入和删除:提供了插入和删除元素的方法,并且可以在任意位置进行操作。
- 支持范围遍历和迭代器:可以使用范围
for
循环或迭代器来遍历容器中的元素。
常用操作:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
// 增加元素
v.push_back(6); // 添加元素6到末尾
// 获取大小
std::cout << "Size: " << v.size() << std::endl; // 6
// 访问元素
std::cout << "Element at index 2: " << v[2] << std::endl; // 3
std::cout << "Element at index 4: " << v.at(4) << std::endl; // 5
// 遍历 vector
for (const int& i : v) {
std::cout << i << " ";
}
std::cout << std::endl;
// 插入元素
v.insert(v.begin() + 2, 10); // 在索引 2 处插入 10
// 删除元素
v.erase(v.begin() + 3); // 删除索引 3 处的元素
// 清空 vector
v.clear();
std::cout << "Is empty: " << v.empty() << std::endl; // 1 (true)
return 0;
}
其他重要函数:
push_back()
,pop_back()
,resize()
,empty()
,clear()
,insert()
,erase()
,front()
,back()
,assign()
总结
std::string
:专为字符串操作设计,提供方便的字符串操作方法,支持自动管理内存。std::vector
:动态数组容器,允许高效的随机访问和动态管理数组大小,适合存储一组相同类型的数据。