Vector实现统计输入单词的个数

// PE3-3--写一个程序,计算输入中每个不同的单词出现了多少次
// 时间:2012-12-19 11:02:35
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using std::cin;         using std::endl;
using std::cout;        using std::vector;
using std::sort;        using std::string;

int main()
{
    cout << "请输入一段文字:" << endl;

    string words;
    vector<string> texts;

    // 不变式:到目前为止,texts包含了所有的单词数
    while (cin >> words && (words != "EOF"))
    {
        texts.push_back(words);
    }·

    // 给输入的单词排序
    sort(texts.begin(), texts.end());

    // 获取总的单词个数
    typedef vector<string>::size_type vec_sz;
    vec_sz size = texts.size();

    // 单词出现次数
    vec_sz cnt;
    vector<vec_sz> count;

    // 不重复的单词
    string words2;
    vector<string> texts2;

    cnt = 0;
    words2 = texts[0];
    texts2.push_back(words2);

    for (vec_sz i=0; i != size; i++)
    {
        if (words2 == texts[i])
        {
            cnt++;
        }
        else
        {
            count.push_back(cnt);

            words2 = texts[i];
            texts2.push_back(words2);

            cnt = 1;
        }
    }

    cout << "出现的单词和对应的次数是:" << endl;
    vec_sz count_sz = count.size();
    for (vec_sz j=0; j != count_sz; ++j)
    {
        cout << texts2[j] <<" "<< count[j] << "次" << endl;
    }

    return 0;
}
 

一道练习题,就是如何使用vector标准容器来实现统计单词的个数,那么我的思路是:

1:首先利用sort函数对其进行排序(标准库的sort效率应该会很高吧!!)

2:利用3个Vector容器。

    1)第一个存放输入的数据;

    2) 第二个存放所有不重复的单词;

    3)   第三个存放重复单词对应的个数。


由于经过排序后,所有相同的单词均排在一起,那么我们就可以很容易的获得不同单词出现的个数。

(未完待续)

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值