You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++滑动窗口统计vector内唯一单词数量报错求助

问题解决:滑动窗口统计vector中窗口内唯一单词数

编译错误原因

你遇到的no match for ‘operator+’错误,是因为vector不支持vector + int的运算。原来参考的数组代码里,arr + i是利用数组名隐式转为指针的特性,得到指向第i个元素的指针;但vector是C++容器,没有定义这种加法运算符,所以不能这么用。

完全不需要把vector转成数组,vector本身就能很好完成这个任务,只需要修改函数的参数传递方式即可。

修改后的完整代码

#include <iostream>
#include <vector>
#include <string>

// 假设你已经实现了以下函数:
// std::vector<std::string> readFile(const std::string&);
// void makeLower(std::vector<std::string>&);
// std::string removeAlpha(const std::string&);

// Counts distinct elements in window of size K
int countWindowDistinct(const std::vector<std::string>& text, int start, int K)
{
    int dist_count = 0;
 
    // 遍历当前窗口:从start到start+K-1
    for (int i = start; i < start + K; ++i) {
        // 检查当前元素是否在窗口的前半部分已出现
        int j;
        for (j = start; j < i; ++j) {
            if (text[i] == text[j]) {
                break;
            }
        }
        if (j == i) {
            dist_count++;
        }
    }
    return dist_count;
}
 
// Counts distinct elements in all windows of size k
void countDistinct(const std::vector<std::string>& text, int N, int K)
{
    // 遍历每个窗口的起始位置
    for (int i = 0; i <= N - K; ++i) {
        std::cout << countWindowDistinct(text, i, K) << std::endl;
    }
}

int main()
{
    std::vector<std::string> book;
    std::vector<std::string> unqWords;

    book = readFile("test.txt");
    makeLower(book);
    
    for (size_t i = 0; i < book.size(); ++i) {
        book[i] = removeAlpha(book[i]);
    }

    const int K = 4;
    const int N = static_cast<int>(book.size()); // 直接用vector的size(),无需额外函数
 
    countDistinct(book, N, K);

    return 0;
}

关键修改点

  1. 函数参数改为const引用:原来的vector<string> text会每次拷贝整个容器,效率极低;改成const std::vector<std::string>& text直接引用原容器,避免拷贝。
  2. 传递窗口起始索引:给countWindowDistinct新增start参数,指定当前窗口在原vector中的起始位置,这样就不需要传递子vector,自然避免了vector + int的错误。
  3. 调整窗口遍历范围:把原来的i从0到K-1改成i从start到start+K-1,确保遍历的是当前窗口内的元素。
  4. 简化size获取:直接用book.size()获取元素个数,不需要额外的calculate_size函数(如果你的calculate_size就是返回size()的话)。

额外优化建议

当前的双重循环时间复杂度是O(NK²),如果你的文本很大,效率会很低。可以用std::unordered_set来统计窗口内的唯一元素,把时间复杂度降到O(NK):

int countWindowDistinct(const std::vector<std::string>& text, int start, int K)
{
    std::unordered_set<std::string> unique_words;
    for (int i = start; i < start + K; ++i) {
        unique_words.insert(text[i]);
    }
    return unique_words.size();
}

甚至可以用滑动窗口的优化技巧,每次窗口移动时只移除离开窗口的元素、添加新进入的元素,把时间复杂度降到O(N),不过对于刚学C++的你,先掌握基础实现即可。

内容的提问来源于stack exchange,提问作者JustBeginning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:35:29