map和set的应用总结


在编程中,我们常常需要使用一些数据结构来管理和操作数据,其中最常用的就是map和set。它们是STL(Standard Template Library)的一部分,提供了许多优秀的算法和数据结构。本文将总结一些使用C++中map和set的常见场景。

1.用map存储键值对

Map是一种非常有用的数据结构,它将两个值配对成一对,一个作为键,一个作为值。例如,我们可以将学生的名字和对应的成绩配对起来。

#include <iostream>
#include <string>
#include <map>

int main()
{
    std::map<std::string, int> grades;
    grades["Alice"] = 80;
    grades["Bob"] = 90;
    grades["Charlie"] = 70;

    std::cout << "Alice's grade is" << grades["Alice"] << std::endl;
    // output: Alice's grade is 80

    return 0;
}

2.用set删除重复项

Set是一种特殊的数据结构,它只能包含唯一值。因此,它经常用于删除重复项。

#include <iostream>
#include <set>
#include <vector>

int main()
{
    std::vector<int> nums = {1, 2, 3, 1, 2, 3, 4, 5};
    std::set<int> unique_nums(nums.begin(), nums.end());

    std::cout << "Unique numbers:" << std::endl;
    for (int num : unique_nums)
    {
        std::cout << num << std::endl;
    }
    // output: Unique numbers: 1 2 3 4 5

    return 0;
}

3.用map和set进行词频统计

在自然语言处理中,我们经常需要统计文本中每个词的出现次数。这可以通过map和set轻松实现。

#include <iostream>
#include <map>
#include <sstream>
#include <string>

std::map<std::string, int> count_words(const std::string& text)
{
    std::map<std::string, int> word_counts;
    std::istringstream iss(text);

    std::string word;
    while (iss >> word)
    {
        ++word_counts[word];
    }

    return word_counts;
}

int main()
{
    std::string text = "the quick brown fox jumps over the lazy dog";

    std::map<std::string, int> word_counts = count_words(text);

    for (const auto& item : word_counts)
    {
        std::cout << item.first << ": " << item.second << std::endl;
    }
    // output: the: 2 quick: 1 brown: 1 fox: 1 jumps: 1 over: 1 lazy: 1 dog: 1

    return 0;
}

总结:

map和set是C++ STL库中非常有用的数据结构。它们可以帮助我们处理复杂的数据结构问题,例如存储和查询关键字、删除重复项、计算词频等等。在实际编程中使用map和set也非常普遍。掌握它们的使用方法,有助于提高代码的质量、可读性和可维护性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值