[英]locate sub-vector<string> in another vector<string>
我有一個vector<string> v1 = {"A","B","C"}
。 我想檢查v1是否included
在vector<string> v2 = {"X","Y","A","B","C","D"}
。
STL
找到一個集合是否是另一個集合的子集? if(counter == v1.size()){break;}
”。 如果子集重復兩次,你認為我應該允許它繼續搜索嗎? #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
float wordOrder ( std::vector<string> v1, std::vector<string> v2 )
{
//declare a vector that will be used as an index. If we find the element of v1 in v2 we insert 1
std::vector<int> index ( v2.size(),0 );
int counter = 0;
int s = v1.size();
//check if size of v1 less than size of V2
if ( v1.size() <= v2.size() ) {
for ( int i = 0; i < v1.size(); i++ ) {
for ( int j = 0; j < v2.size(); j++ ) {
if ( v1[i]== v2[j]) {index[j] = 1;}
}
}
//loop throught the index vector and check if we have a sequence of 1s
for ( int i = 0; i < index.size(); i++ ) {
if ( index[i] == 1 ) {
for ( int j = i; j < index.size(); j++ ) {
if ( index[j] == 1 ) {counter++;}
}
//if the sequence of 1s = to the size of v1 it means that we have identified the sub-vector
if(counter == v1.size()){break;}
else{counter = 0; continue;}
}
}
}//end if
return counter/(float)v1.size();
}
int main()
{
std::vector<string> v1{"A","B","C"};
std::vector<string> v2{"X","A","B","C","Y"};
cout << wordOrder (v1, v2 ) << endl;
return 0;
}
RE:我可以通過使用STL找到一個集合是否是另一個集合的子集?
答案是肯定的,但可能沒有你想要的那么性感。 您可以使用count_if迭代v2並提供一個函數來計算子集在該容器中出現的頻率。 如果您要搜索的子集將始終按順序出現(即C跟隨B跟隨A,否則它不計算),您可以使用search_n()或search()。
RE:如果僅在算法停止“if(counter == v1.size()){break;}”時找到子集。 如果子集重復兩次,你認為我應該允許它繼續搜索嗎?
這取決於您的需求。 你需要那個功能嗎? 如果是這樣,那么你應該編程。 如果不這樣做,現有功能就足夠,簡單,高效,因此更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.