【问题标题】:Word count program in C++ [duplicate]C ++中的字数统计程序[重复]
【发布时间】:2011-05-26 08:29:13
【问题描述】:

可能重复:
Count the number of times each word occurs in a file

嗨,
我已经很久没有进行 C++ 编程了。
这可能是一个非常愚蠢的问题。
我在这个网站上找到了几个关于字数统计的程序。
但他们中的大多数人都使用std::string 作为他们的密钥。
就我而言,我需要使用 char* 作为我的密钥。
但似乎由于每个char* 具有不同的地址值,重复的键被插入到我的地图中。

char str[] = "This This";
typedef std::map<char*, int> word_count_t;
typedef word_count_t::iterator word_count_iter_t;

int _tmain(int argc, _TCHAR* argv[])
{
    char *token = strtok(str, " ");
    word_count_t word_count;
    word_count_iter_t itr = NULL;

    while(token) {
        ++word_count[token];
        token = strtok(NULL, " ");
    }

    for(itr = word_count.begin(); itr != word_count.end(); itr++) {
        std::cout << "Key: " << itr->first  << ", Value: " << itr->second << std::endl;
    }

    getchar();
}

我得到的这个程序的输出是

键:这个,值:1
键:这个,值:1

我想要像这样的输出

键:这个,值:2

谁能告诉我我错过了什么?

谢谢。

【问题讨论】:

  • 一个 Map 不能有重复的键,你应该使用 multimap。
  • @Als 他不想要重复的键。
  • @Nawaz 除了他没有计算文件中的单词。

标签: c++


【解决方案1】:

您想要一个std::map&lt;std::string, int&gt; - 您的char* 映射将比较指针而不是它们指向的字符串。

【讨论】:

    【解决方案2】:

    std::map 默认情况下使用operator &lt; 键类型进行比较。 operator &lt; on char * 比较指针地址,而不是字符串的字符。

    您想改用std::map&lt;std::string, int&gt;,因为std::string 上的operator &lt; 会进行词法字符串比较。

    【讨论】:

      【解决方案3】:

      您必须为const char * 创建自己的比较类:

      struct StrCmp {
          static bool operator() (const char *a, const char *b) {
              return strcmp(a, b)<0;
          }
      };
      

      然后你可以使用地图:

      typedef std::map<char const *, int, StrCmp> word_count_t;
      

      【讨论】:

        【解决方案4】:

        首先,您应该真正使用一些 HashMap 实现。 std::map 是一个 TreeMap 并且在计算大量文本中的单词时会变慢。这是因为文本中出现的大量单词将映射到适量的不同单词。即使您需要对输出进行排序,之后对哈希图进行排序也会更好,因为插入树将是 #occurrences * log #words 而对它们进行排序将是 O(#words * log #words)

        除此之外,大多数 hashmap 实现(我个人通常使用 google::dense_hash_map 或 google::sparse_hash_map)可以处理 char*,而无需编写散列函数(它们使用 stl 散列函数)。所以它基本上是即插即用的。

        【讨论】:

          【解决方案5】:

          键是不同的,因为它们是char*,即指向内存中不同位置的指针。如果您使用std::map&lt;std::string, int&gt; 并执行++word_count[std::string(token)],您将获得预期的输出。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-10-08
            • 1970-01-01
            • 2014-06-18
            • 2012-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多