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; }
关键修改点
- 函数参数改为const引用:原来的
vector<string> text会每次拷贝整个容器,效率极低;改成const std::vector<std::string>& text直接引用原容器,避免拷贝。 - 传递窗口起始索引:给
countWindowDistinct新增start参数,指定当前窗口在原vector中的起始位置,这样就不需要传递子vector,自然避免了vector + int的错误。 - 调整窗口遍历范围:把原来的
i从0到K-1改成i从start到start+K-1,确保遍历的是当前窗口内的元素。 - 简化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
相关产品推荐
相关产品推荐

