C ++计数和映射 [英] C++ count and map

查看:91
本文介绍了C ++计数和映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计算一个文本文件中每个字出现的次数。我想避免的情况,因此我做下来我的输入,然后计数。我有一个地图数据结构有string和int保持计数。现在,当我输出单词及其计数时,我不希望单词以小写形式出现,但希望它保持原来的情况。所以,对于计数所有的单词应该更改为小写,但给出输出,他们都应该在他们的原始case。 cd:std的第三个模板参数:

解决方案

:map 是一个比较器类型。您可以提供自己的比较操作,在大小写不敏感的情况下。

  struct CaseInsensitive {
bool operator ()(std :: string const& left,std :: string const& right)const {
size_t const size = std :: min(left.size(),right.size());

for(size_t i = 0; i!= size; ++ i){
char const lowerLeft = std :: tolower(left [i]);
char const lowerRight = std :: tolower(right [i]);

if(lowerLeft< lowerRight){return true; }
if(lowerLeft> lowerRight){return false; }

//如果相等?继续!
}

//相同的前缀?那么我们比较长度
return left.size()<合适的尺码();
}
};

然后实现您的地图:

  typedef std :: map< std :: string,unsigned,CaseInsensitive> MyWordCountingMap; 

注意:只保留第一个拼字$ b

I am counting the number of times every word occurs in a text file. I would like to avoid cases and hence am doing tolower to my input and then counting. I have a map data structure having string and int to keep count. Now, when I output the word and its count, I don't want the word to be in lower case, but want it to maintain its original case. So, for counting all the words should change to lowercase but while giving output they all should be in their original case. Is there anyway to achieve this with using only one map?

解决方案

The third template parameter of std::map is a comparator type. You can provide your own comparison operation, in your case a case-insensitive one.

struct CaseInsensitive {
  bool operator()(std::string const& left, std::string const& right) const {
    size_t const size = std::min(left.size(), right.size());

    for (size_t i = 0; i != size; ++i) {
      char const lowerLeft = std::tolower(left[i]);
      char const lowerRight = std::tolower(right[i]);

      if (lowerLeft < lowerRight) { return true; }
      if (lowerLeft > lowerRight) { return false; }

      // if equal? continue!
    }

    // same prefix? then we compare the length
    return left.size() < right.size();
  }
};

Then instanciate your map:

typedef std::map<std::string, unsigned, CaseInsensitive> MyWordCountingMap;

Note: only the first spelling is preserved (which seems okay with you)

这篇关于C ++计数和映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆