关于STL容器这一块,我确实有比较深入的了解。让我从最基础的vector开始,然后系统地讲一下其他容器。
STL 三大核心概念-容器、算法、迭代器。容器和迭代器是一一对应的,迭代器作为容器和算法的统一接口。

std::string

#include <iostream>
#include <string> // 必须包含string头文件
#include <cctype> // 用于字符处理函数

int main() {
    std::cout << "=== C++ std::string 完整用法示例 ===" << std::endl << std::endl;

    // ==================== 1. 字符串的构造与初始化 ====================
    std::cout << "1. 字符串构造与初始化:" << std::endl;
    std::string s1; // 默认构造,空字符串
    std::string s2 = "Hello, World!"; // 从C风格字符串拷贝构造
    std::string s3("Hello, C++!"); // 直接初始化
    std::string s4(s2); // 拷贝构造
    std::string s5(10, 'A'); // 填充构造,10个'A'
    std::string s6(s2, 7, 5); // 子串构造,从s2索引7开始,取5个字符 -> "World"

    std::cout << "s1 (空): \"" << s1 << "\"" << std::endl;
    std::cout << "s2: \"" << s2 << "\"" << std::endl;
    std::cout << "s3: \"" << s3 << "\"" << std::endl;
    std::cout << "s4 (s2的拷贝): \"" << s4 << "\"" << std::endl;
    std::cout << "s5 (10个A): \"" << s5 << "\"" << std::endl;
    std::cout << "s6 (s2的子串): \"" << s6 << "\"" << std::endl << std::endl;

    // ==================== 2. 字符串赋值 ====================
    std::cout << "2. 字符串赋值:" << std::endl;
    s1 = "直接赋值"; // 操作符赋值
    s2.assign("使用assign方法赋值"); // assign方法赋值
    s3.assign(s2, 0, 6); // 从s2赋值部分字符 -> "使用ass"
    s4.assign(5, 'X'); // 赋值5个'X'

    std::cout << "s1: \"" << s1 << "\"" << std::endl;
    std::cout << "s2: \"" << s2 << "\"" << std::endl;
    std::cout << "s3: \"" << s3 << "\"" << std::endl;
    std::cout << "s4: \"" << s4 << "\"" << std::endl << std::endl;

    // ==================== 3. 字符串访问与遍历 ====================
    std::cout << "3. 字符串访问与遍历:" << std::endl;
    std::string str = "ABCDE";

    // 使用下标操作符 []
    std::cout << "str[0]: '" << str[0] << "'" << std::endl;
    
    // 使用at()方法 (会进行边界检查)
    std::cout << "str.at(1): '" << str.at(1) << "'" << std::endl;
    
    // 获取首字符和尾字符
    std::cout << "str.front(): '" << str.front() << "'" << std::endl;
    std::cout << "str.back(): '" << str.back() << "'" << std::endl;

    // 遍历方法1: 使用下标
    std::cout << "下标遍历: ";
    for (size_t i = 0; i < str.length(); ++i) {
        std::cout << str[i] << " ";
    }
    std::cout << std::endl;

    // 遍历方法2: 使用迭代器
    std::cout << "迭代器遍历: ";
    for (auto it = str.begin(); it != str.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    // 遍历方法3: 范围for循环 (C++11)
    std::cout << "范围for循环: ";
    for (char c : str) {
        std::cout << c << " ";
    }
    std::cout << std::endl << std::endl;

    // ==================== 4. 字符串容量相关 ====================
    std::cout << "4. 字符串容量操作:" << std::endl;
    std::string capacity_str;
    
    std::cout << "初始状态 - 长度: " << capacity_str.length() 
              << ", 容量: " << capacity_str.capacity() 
              << ", 是否为空: " << (capacity_str.empty() ? "是" : "否") << std::endl;
    
    capacity_str = "这是一个测试字符串";
    std::cout << "赋值后 - 长度: " << capacity_str.length() 
              << ", 容量: " << capacity_str.capacity() 
              << ", 是否为空: " << (capacity_str.empty() ? "是" : "否") << std::endl;
    
    capacity_str.reserve(100); // 预留容量
    std::cout << "reserve(100)后 - 容量: " << capacity_str.capacity() << std::endl;
    
    capacity_str.shrink_to_fit(); // 收缩到合适大小 (C++11)
    std::cout << "shrink_to_fit()后 - 容量: " << capacity_str.capacity() << std::endl << std::endl;

    // ==================== 5. 字符串修改操作 ====================
    std::cout << "5. 字符串修改操作:" << std::endl;
    
    // 追加
    std::string mod_str = "Hello";
    mod_str += " World"; // 操作符追加
    mod_str.append("!!!"); // append方法追加
    mod_str.push_back('*'); // 追加单个字符
    std::cout << "追加后: \"" << mod_str << "\"" << std::endl;
    
    // 插入
    mod_str.insert(5, " C++"); // 在位置5插入
    std::cout << "插入后: \"" << mod_str << "\"" << std::endl;
    
    // 删除
    mod_str.erase(5, 4); // 从位置5开始删除4个字符
    std::cout << "删除后: \"" << mod_str << "\"" << std::endl;
    
    // 替换
    mod_str.replace(6, 5, "STL"); // 从位置6开始替换5个字符为"STL"
    std::cout << "替换后: \"" << mod_str << "\"" << std::endl;
    
    // 清空
    mod_str.clear();
    std::cout << "清空后: \"" << mod_str << "\"" << std::endl << std::endl;

    // ==================== 6. 字符串操作 ====================
    std::cout << "6. 字符串操作:" << std::endl;
    std::string main_str = "Hello, World! Welcome to C++ Programming.";
    
    // 子串
    std::string sub = main_str.substr(7, 5); // 从位置7开始取5个字符
    std::cout << "子串(7,5): \"" << sub << "\"" << std::endl;
    
    // 查找
    size_t pos = main_str.find("C++"); // 查找子串位置
    if (pos != std::string::npos) {
        std::cout << "找到 'C++' 在位置: " << pos << std::endl;
    }
    
    // 反向查找
    pos = main_str.rfind('o'); // 从后向前查找字符
    std::cout << "最后一个 'o' 在位置: " << pos << std::endl;
    
    // 查找第一个出现的字符
    pos = main_str.find_first_of("aeiou"); // 查找第一个元音字母
    std::cout << "第一个元音字母在位置: " << pos << std::endl;
    
    // 查找第一个不出现的字符
    pos = main_str.find_first_not_of("Helo, Wrd!"); // 查找第一个不在集合中的字符
    std::cout << "第一个不在\"Helo, Wrd!\"中的字符在位置: " << pos << std::endl << std::endl;

    // ==================== 7. 字符串比较 ====================
    std::cout << "7. 字符串比较:" << std::endl;
    std::string a = "apple";
    std::string b = "banana";
    std::string c = "apple";
    
    // 使用比较操作符
    std::cout << "\"apple\" == \"banana\": " << (a == b ? "真" : "假") << std::endl;
    std::cout << "\"apple\" == \"apple\": " << (a == c ? "真" : "假") << std::endl;
    std::cout << "\"apple\" < \"banana\": " << (a < b ? "真" : "假") << std::endl;
    
    // 使用compare方法 (返回0表示相等,<0表示小于,>0表示大于)
    int result = a.compare(b);
    std::cout << "\"apple\".compare(\"banana\"): " << result << std::endl << std::endl;

    // ==================== 8. 字符串与数值转换 ====================
    std::cout << "8. 字符串与数值转换:" << std::endl;
    
    // 数字转字符串 (C++11)
    int num = 42;
    double pi = 3.14159;
    std::string num_str = std::to_string(num);
    std::string pi_str = std::to_string(pi);
    std::cout << "数字转字符串: " << num_str << ", " << pi_str << std::endl;
    
    // 字符串转数字 (C++11)
    std::string year_str = "2024";
    std::string price_str = "19.99";
    int year = std::stoi(year_str);
    double price = std::stod(price_str);
    std::cout << "字符串转数字: " << year << ", " << price << std::endl << std::endl;

    // ==================== 9. 输入输出操作 ====================
    std::cout << "9. 输入输出操作:" << std::endl;
    
    // 使用getline读取整行(包括空格)
    std::string input;
    std::cout << "请输入一行文本: ";
    std::getline(std::cin, input); // 读取整行
    std::cout << "您输入的是: \"" << input << "\"" << std::endl << std::endl;

    // ==================== 10. C风格字符串转换 ====================
    std::cout << "10. C风格字符串转换:" << std::endl;
    std::string cpp_str = "C++ String";
    
    // 转换为C风格字符串 (以空字符结尾)
    const char* c_str = cpp_str.c_str();
    std::cout << "C风格字符串: " << c_str << std::endl;
    
    // 获取字符数组指针 (C++17)
    const char* data_ptr = cpp_str.data();
    std::cout << "数据指针: " << data_ptr << std::endl << std::endl;

    // ==================== 11. 字符串流操作 ====================
    std::cout << "11. 字符串流操作 (需要#include <sstream>):" << std::endl;
    #include <sstream>
    
    std::stringstream ss;
    ss << "姓名: 张三, 年龄: " << 25 << ", 分数: " << 95.5;
    std::string formatted_str = ss.str();
    std::cout << "格式化字符串: " << formatted_str << std::endl;

    return 0;
}

std::vector

std::vector

std::vector本质上是一个动态数组,在堆上分配连续的内存空间。里面通过三个指针来管理:指向开头、指向当前元素末尾,和指向分配容量的末尾。当元素数量达到容量上限时,vector会进行扩容,这通常是将容量翻倍,然后分配新的更大内存,把老数据搬过去,释放旧内存。

这里有个很重要的点就是迭代器失效——扩容后所有的迭代器、指针都会失效,因为元素可能被搬到了新的地址。这也是为什么在循环中插入元素要特别小心。

**关于STL容器分成:序列容器像vector、deque、list这些;关联容器比如map、set;还有无序关联容器unordered_map这些;以及容器适配器像stack、queue。

每种容器底层实现都不一样,比如vector是动态数组,deque是分段连续空间,list是双向链表,而map和set这些通常是用红黑树实现的。

说到map为什么用红黑树而不用AVL树,这其实是个很好的设计权衡问题。虽然AVL树查询性能稍微好一点,因为它更平衡,但红黑树在插入删除时的旋转操作要少得多。红黑树最多旋转3次,而AVL可能需要O(log n)次。考虑到STL的map需要频繁的插入删除,红黑树在综合性能上更有优势,查询性能的损失也不大。

这自然就引出了map和unordered_map的区别问题,最核心的区别就是map基于红黑树,元素是有序的,操作时间复杂度是O(log n);而unordered_map基于哈希表,元素无序,但平均时间复杂度是O(1)。选择哪个要看具体场景:如果需要有序遍历或者键类型比较复杂,用map;如果对性能要求极高且有好的哈希函数,用unordered_map。

STL容器默认都不是线程安全的。如果多个线程同时读写同一个容器,需要我们自己加锁。在读多写少的场景下,可以考虑用读写锁来优化性能。

最后说到优先队列,它其实是个容器适配器,默认基于vector实现成一个最大堆。通过堆的上浮和下沉操作来维护优先级,插入删除是O(log n),获取顶部元素是O(1),很适合做任务调度这类场景。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐