C++ count and map

前端 未结 5 1119
难免孤独
难免孤独 2021-01-22 21:54

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 struc

5条回答
  •  悲&欢浪女
    2021-01-22 23:01

    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 MyWordCountingMap;
    

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

提交回复
热议问题