一个关于容器使用的段子 学习一下

本文介绍了一个使用C++模板实现的字符串单词计数程序。该程序定义了WordCount结构体来存储单词及其出现次数,并通过自定义操作符重载简化了输入输出及比较操作。此外,还提供了一个word_count函数用于统计给定字符串数组中各个单词的出现频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <typename T>
istream& operator>>(istream& is, vector<T>& vec)
{
    T temp;
    while (is >> temp)
        vec.push_back(temp);
    return is;
}

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& vec)
{
    typename vector<T>::const_iterator first = vec.begin();
    while (first != vec.end())
        os << *first++ << " ";
    os << endl;
    return os;
}

struct WordCount {
    string word;
    int    count;
};

// 重载WordCount的<<操作符
ostream& operator<<(ostream& os, const WordCount& value)
{
    os << value.word << ":" << value.count;
    return os;
}

// 重载WordCount与string的==操作符
bool operator==(const WordCount& lhs, const string& rhs)
{
    return lhs.word == rhs;
}

// 在WordCount数组中查找指定的单词所在元素位置
template <typename InputIterator>
InputIterator find_word(InputIterator first, InputIterator last,
                        const string& value)
{
    while (first != last && !(*first == value))
        ++first;
    return first;
}

// 统计words数组中每个单词出现的次数,存入result数组中
void word_count(const vector<string>& words,
                vector<WordCount>& result)
{
    vector<string>::const_iterator iter = words.begin();
    for (; iter != words.end(); ++iter) { // 遍历单词表
        vector<WordCount>::iterator it = find_word(result.begin(), result.end(), *iter);
        if (it == result.end()) {  // 结果数组中不存在该单词
              WordCount temp;
            temp.count = 1;
            temp.word = *iter;
            result.push_back(temp);
        }
        else // 结果数组中已存在该单词,计数器加1
            ++(it->count);
    }
}

int main()
{
    vector<string> words;
    cin >> words; // Ctrl-Z(eof)结束输入
     vector<WordCount> vec;
    word_count(words, vec);
    cout << vec;
 Sleep(100000);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值