如何解决计算一个向量在另一个向量中完全出现的次数
我正在编写一个简单的函数,该函数返回一个整数,指示整数 一个向量的内容出现在另一个向量中。
例如:
vector<int> v1 {1,4,2,1,9,2};
vector<int> v2 {1,2};
cout << countOccurrences(v1,v2);
应返回4。
这是我的迭代解决方案
int countOccurrences(vector<int> &v1,vector<int> &v2) {
int i,j,count = 0;
for(i = 0; i <= v1.size() - v2.size(); ++i) {
for(j = 0; j < v2.size(); ++j) {
if(v1[i + j] != v2[j])
break;
}
if(j == v2.size())
++count;
}
return count;
}
我想递归地编写相同的函数,但我一无所知。我是递归的新手,这似乎令我感到恐惧。
解决方法
这是一种方式(用伪代码):
int countOccurrences(vector<int> &v1,vector<int> &v2) {
if v1 is shorter than v2
return 0;
if v1 starts with v2
return 1 + countOccurrences( v1[1:],v2 )
else
return countOccurrences( v1[1:],v2 );
}
,
如果使用迭代器,递归会更容易一些
template <typename IT>
int count_occurences(IT begin,IT end,IT s_begin,IT s_end) {
auto it = std::search(begin,end,s_begin,s_end);
auto dist = std::distance(s_begin,s_end);
if (it == end) return 0;
return 1 + count_occurences(it+dist,s_end);
}
std::search
在另一个范围[s_begin,s_end)
中搜索一个范围[begin,end)
。我想您不想使用它,所以我将其留给您,用您手写的方式替换它,以便在其中找到一个。递归是通过在发现序列时累加1
来发挥作用的,并仅在向量的其余部分再次调用该函数。
然而,一个c ++ 20解决方案:
#include <vector>
#include <span>
#include <algorithm>
int countOccurrences(std::span<int> data,std::span<int> needle)
{
if (data.size() < needle.size())
return 0;
if (std::equal(needle.begin(),needle.end(),data.begin()))
return 1 + countOccurrences(data.subspan(1),needle);
else
return countOccurrences(data.subspan(1),needle);
}
int main()
{
std::vector<int> data{ 1,4,2,1,9,2 };
std::vector<int> needle{ 1,2 };
printf_s("%d\n",countOccurrences(data,needle));
}
这比每次递归使用子向量要快得多,因为它只是一个视图!没有分配!
,此代码基于Scott Hunter提供的伪代码。
bool start_with(vector<int> &v1,vector<int> &v2) {
for(auto i = 0; i < v2.size(); ++i)
if (v1[i] != v2[i])
return false;
return true;
}
int countOccurrences(vector<int> &v1,vector<int> &v2) {
static int i = 0;
if(v1.size() < v2.size()) {
return 0;
}
else if(start_with(v1,v2)) {
vector<int> temp(v1.begin() + i + 1,v1.end());
return 1 + countOccurrences(temp,v2);
}
vector<int> temp(v1.begin() + i + 1,v1.end());
return countOccurrences(temp,v2);
}
随时建议不改变功能原型的惰性黑客替代方法,例如static variable
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。