C++中STL容器应用

一、STL容器核心应用

1. vector(动态数组)

特性:连续内存、随机访问O(1)、尾部操作高效

// 高性能数值计算
vector<double> processSensorData() {
   
    vector<double> readings;
    readings.reserve(1000);  // 预分配内存避免多次扩容

    for(int i=0; i<1000; ++i) {
   
        readings.push_back(getSensorValue());
    }

    // 使用STL算法处理数据
    auto max_val = *max_element(readings.begin(), readings.end());
    transform(readings.begin(), readings.end(), readings.begin(),
             [max_val](double x) {
    return x/max_val; });

    return readings;
}

// 二维数组模拟
vector<vector<int>> matrix(5, vector<int>(5, 0));  // 5x5矩阵初始化
 
 

2. list(双向链表)

特性:任意位置插入/删除O(1)、不支持随机访问

// 高频交易订单簿
struct Order {
   
    double price;
    int quantity;
};

list<Order> orderBook;

// 插入时自动排序
void addOrder(Order newOrder) {
   
    auto it = find_if(orderBook.begin(), orderBook.end(),
                     [&](const Order& o) {
    return o.price > newOrder.price; });
    orderBook.insert(it, newOrder);
}

// 快速删除失效订单
orderBook.remove_if([](const Order& o) {
    return o.quantity <= 0; });
 
 

3. map/set(红黑树实现)

特性:自动排序、查找O(log n)

// 字典管理
map<string, string> configMap = {
   
    {
   "resolution", "1920x1080"},
    {
   "volume", "75"}
};

// 安全访问
if(auto it = configMap.find("volume"); it != configMap.end()) {
   
    cout << "当前音量:" << it->second << endl;
}

// 多键索引
multimap<string, Employee> nameIndex;  // 允许重复键
 
 

4. unordered_map(哈希表)

特性:平均O(1)访问、无序存储

// 快速查找表
unordered_map<string, int> wordCount;

// 词频统计
string text = "a quick brown fox jumps over the lazy dog";
istringstream iss(text);
string word;
while(iss >> word) {
   
    ++wordCount[word];
}

// 查找高频词
auto highFreq = max_element(wordCount.begin(), wordCount.end(),
                           [](auto& a, auto& b) {
    return a.second < b.second; });
 
 

5. deque(双端队列)

特性:头尾操作高效、分段连续存储

// 滑动窗口处理
deque<int> window;
const int WINDOW_SIZE = 5;

void processData(int newValue) {
   
    window.push_back(newValue);
    if(window.size() > WINDOW_SIZE) {
   
        window.pop_front();
    }

    // 计算窗口平均值
    double avg = accumulate(window.begin(), window.end(), 0.0) / window.size();
}
 
 

常见陷阱与解决方案

  1. 迭代器失效问题
    vector<int> vec {
         1,2,3,4,5};
    for(auto it = vec.begin(); it != vec.end(); ) {
         
     if(*it % 2 == 0) {
         
         it = vec.erase(it);  // 正确方式
     } else {
         
         ++it;
     }
    }
posted @ 2025-10-28 11:19  荒川之主  阅读(1)  评论(0)    收藏  举报