请举出你使用STL解决过的实际问题。

问题描述

假设我们需要开发一个简单的通讯录管理系统。这个系统需要能够添加新联系人、删除联系人、查找特定联系人,并且按字母顺序显示所有联系人。

解决方案

我们可以使用 C++ STL 中的容器和算法来实现这个系统。

使用的 STL 组件
  • std::vector: 存储联系人信息。
  • std::sort: 对联系人按名字排序。
  • std::find_if: 查找特定的联系人。
  • std::remove_if: 从列表中删除特定的联系人。
示例代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Contact {
    std::string name;
    std::string phone;
};

int main() {
    std::vector<Contact> contacts;

    // 添加联系人
    contacts.push_back({"Alice", "123-4567"});
    contacts.push_back({"Bob", "234-5678"});
    contacts.push_back({"Carol", "345-6789"});

    // 排序联系人
    std::sort(contacts.begin(), contacts.end(), [](const Contact& a, const Contact& b) {
        return a.name < b.name;
    });

    // 查找联系人
    auto it = std::find_if(contacts.begin(), contacts.end(), [](const Contact& c) {
        return c.name == "Alice";
    });
    if (it != contacts.end()) {
        std::cout << "Found: " << it->name << " - " << it->phone << '\n';
    }

    // 删除联系人
    contacts.erase(std::remove_if(contacts.begin(), contacts.end(), [](const Contact& c) {
        return c.name == "Bob";
    }), contacts.end());

    // 打印所有联系人
    for (const auto& contact : contacts) {
        std::cout << contact.name << " - " << contact.phone << '\n';
    }
}

在这个例子中,我们使用 std::vector 存储联系人信息。使用 std::sort 对联系人进行排序,std::find_if 查找特定联系人,以及 std::remove_if 结合 std::vector::erase 删除联系人。这个系统能有效地管理联系人信息,并且展示了 STL 在数据管理和操作上的强大功能。

发表评论

后才能评论