首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >统计vector<string>中的单词出现次数

统计vector<string>中的单词出现次数
EN

Stack Overflow用户
提问于 2014-05-08 19:05:36
回答 1查看 1.5K关注 0票数 0

我有一个家庭作业,其中我必须制作一个c++应用程序,该应用程序可以通过参数从cmd调用。有3个参数:

第一个方法获取所有不带标点符号的单词,将它们转换为lower并按字母顺序存储。所以我使用了一个向量字符串。

第二个计算文件中每个单词的出现次数,并对它们进行排序,以便最常使用的单词排在第一位。我被困在这一部分,不知道该如何处理..所以如果有人能帮我的话我将非常感激

第三个参数统计每个punctuation..same的出现次数,正如你可以想象的那样,我也被这部分卡住了哈哈这是我到目前为止的代码:

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>


using namespace std;


int main(int argc, char* argv[])
{
ifstream ulaz ("korpus.txt");
string testline;
vector<string> word;

if (string(argv[1])=="-r"){
    cout<<"uzima rijeci iz korpusa i stavlja u rijecnik po abecedi"<<endl;
    while(ulaz >> testline)
    {
        for(int i=0; i<testline.size(); i++){
                if (ispunct(testline[i])) testline.erase(i);
        }
    transform (testline.begin(), testline.end(), testline.begin(), ::tolower);
    word.push_back(testline);
    }
    sort(word.begin(), word.end());
    for (int i=0; i<word.size(); i++) {
            cout<<word[i]<<"("<<i<<")"<<endl;
    }
}


if (string(argv[1])=="-f"){
    cout<<endl<<"frekventonost ponavljanja se izračunava"<<endl;
}
if (string(argv[1])=="-i"){
    cout<<endl<<"broj interpunkcija i sranja se izračunava"<<endl;

}
return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2014-05-08 19:16:09

您可以使用map或unordered_map创建单词计数器:

代码语言:javascript
复制
std::map<std::string, unsigned int> counter;
for (auto w : word)
{
    counter[w]++;
}

然后,您只需要按计数对map的元素进行排序。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23539983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档