首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

我如何编写一个函数来检查一个单词在向量中是否重复了两次或更多,并输出它重复的次数?在C++中

在C++中,可以编写一个函数来检查一个单词在向量中是否重复了两次或更多,并输出它重复的次数。以下是一个示例代码:

代码语言:txt
复制
#include <iostream>
#include <vector>
#include <unordered_map>

int checkWordDuplicates(const std::vector<std::string>& words, const std::string& targetWord) {
    std::unordered_map<std::string, int> wordCount;

    // 统计每个单词出现的次数
    for (const std::string& word : words) {
        wordCount[word]++;
    }

    // 检查目标单词是否重复,并输出重复次数
    if (wordCount.find(targetWord) != wordCount.end()) {
        int count = wordCount[targetWord];
        if (count >= 2) {
            return count;
        }
    }

    return 0; // 目标单词未重复
}

int main() {
    std::vector<std::string> words = {"apple", "banana", "apple", "orange", "apple"};
    std::string targetWord = "apple";

    int duplicateCount = checkWordDuplicates(words, targetWord);
    std::cout << "The word \"" << targetWord << "\" is repeated " << duplicateCount << " times." << std::endl;

    return 0;
}

这个函数使用了一个无序映射 std::unordered_map 来统计每个单词出现的次数。然后,它检查目标单词是否在映射中,并返回重复的次数。如果重复次数大于等于2,则表示目标单词重复了两次或更多。

这个函数的时间复杂度为 O(n),其中 n 是向量中的单词数量。它可以适用于任何类型的单词向量,并且可以轻松地扩展到检查多个单词是否重复。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版:https://cloud.tencent.com/product/cdb_mysql
  • 云原生应用引擎(TKE):https://cloud.tencent.com/product/tke
  • 云存储(COS):https://cloud.tencent.com/product/cos
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 移动推送服务(信鸽):https://cloud.tencent.com/product/tpns
  • 区块链服务(BCS):https://cloud.tencent.com/product/bcs
  • 腾讯云元宇宙:https://cloud.tencent.com/solution/virtual-universe 请注意,这些链接仅供参考,具体的产品选择应根据实际需求进行评估。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券