在另一个向量<string> </string> </string>中找到子向量<string>

时间:2014-06-24 14:09:53

标签: c++ vector set substring

我有vector<string> v1 = {"A","B","C"}。我想检查included中的v1是vector<string> v2 = {"X","Y","A","B","C","D"}

  • 我可以使用STL
  • 查找某个集合是否是另一个集合的子集
  • 不应对矢量进行排序
  • 如果找到子集一次,则算法停止&#34; if(counter == v1.size()){break;}&#34 ;.如果子集重复两次,你认为我应该允许它继续搜索吗?

#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;
}

2 个答案:

答案 0 :(得分:11)

是的,您可以使用标准库。使用std::search执行range 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);

直播示例here

答案 1 :(得分:1)

RE:我可以使用STL找到一个集合是否是另一个集合的一部分吗?

答案是肯定的,但可能没有你想要的那样性感。您可以使用count_if迭代v2并提供一个函数来计算子集在该容器中出现的频率。如果您要搜索的子集将始终按顺序出现(即C跟随B跟随A,否则它不计算),您可以使用search_n()或search()。

RE:如果只在算法停止“if(counter == v1.size()){break;}”时找到子集。如果子集重复两次,你认为我应该允许它继续搜索吗?

这取决于您的需求。你需要那个功能吗?如果是这样,那么你应该编程。如果不这样做,现有功能就足够,简单,效率更高,因此更好。