定位子向量< string>在另一个向量< string> [英] locate sub-vector<string> in another vector<string>
本文介绍了定位子向量< string>在另一个向量< string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量< string> v1 = {A,B,C}
。我想检查在中是否包含
。
vector< string> v2 = {X,Y,A,B,C,D}
I have a vector<string> v1 = {"A","B","C"}
. I want to check if v1 is included
in vector<string> v2 = {"X","Y","A","B","C","D"}
.
- 我可以使用
STL
吗? - 我可以找到一个集合是否是另一个集合的子集不排序
- 如果发现子集只是一次,算法停止
if(counter == v1.size()){ break;}
。您认为我应该允许它继续搜索,以防子集重复两次?
- Can I find if a set is a subset of the other by using
STL
? - The vectors should not be sorted
- If the subset is found just once the algorithm stops "
if(counter == v1.size()){break;}
". Do you think that I should allow it to continue the search in case the subset is repeated twice?
#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;
}
推荐答案
图书馆。使用 std :: search
执行范围搜索:
vector<string> v1 = {"A","B","C"};
vector<string> v2 = {"X","Y","A","B","C","D"};
auto res = search(begin(v2), end(v2), begin(v1), end(v1));
并测试是否找到范围:
auto found = res != end(v2);
Live example 此处。
Live example here.
这篇关于定位子向量< string>在另一个向量< string>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文