查找第二个向量中是否包含1个向量

时间:2015-12-13 19:54:10

标签: c++

我需要编写一个程序,找出其中一个向量是否包含在另一个向量中。 该计划的工作原理如下。

1 - 从m(第1行)获取ninput.txt

2 - 将verctorMvectorN调整为mn,然后使用input.txt中的数字填充它们(vectorM的第2行,vectorN)的第3行

3 - 填充后,程序应该发现其中一个向量具有最少的#34;字符"通过比较nm

4 - 该程序获得第一个"字符" "小"矢量并开始将它与"字符进行比较" "大" vector()

5 - 当状态vectorN[i] = vectorM[0]正确时,程序会比较下一个"字符"如果每个"字符" "小"矢量是在"大"向量,程序输出1,如果没有继续与第一个" caracter" " smal"矢量,如果"小"矢量不包括在"大"向量,节目输出0

编辑 - 数字必须与input.txt

中所写的顺序相同

以下是我最终的代码

#include <iostream> 
#include <vector>
#include <fstream>
using namespace std;

int main() {

int m;
int n;

bool y = false;

vector<int> vectorM;
vector<int> vectorN;

ifstream file1;
file1.open("input.txt");
file1 >> m;
file1 >> n;

vectorM.resize(m);
vectorN.resize(n);

for (int i = 0; i < m; i++){
    file1 >> vectorM[i];
}

for (int i = 0; i < n; i++){
    file1 >> vectorN[i];
}

//this is the part that I need help with


ofstream file2;
file2.open("output.txt");

if (y == false)
    file2 << 0;
else
    file2 << 1;

}

比较&#34;字符&#34;的有效方法是什么? ??

示例,如果在input.txt

 4 3
 1 2 3 2
 1 2 3

节目输出1,因为1 2 3在1 2 3 2中,但是如果

 2 3
 1 2
 2 3 1

节目输出0

1 个答案:

答案 0 :(得分:4)

我认为你在询问是否可以在另一个值范围内找到连续的子序列。标准库std::search算法就是这样做的。

#include <algorithm>
#include <iostream>
#include <vector>

bool included(const std::vector<int>& seq, const std::vector<int>& sub)
{
    return std::search(seq.begin(), seq.end(), sub.begin(), sub.end()) != seq.end();
}

int main()
{
    auto v1 = std::vector<int>{ 1,2,3,2 };
    auto v2 = std::vector<int>{ 1,2,3 };

    std::cout << std::boolalpha << included(v1, v2) << '\n';

    auto v3 = std::vector<int>{ 1,2 };
    auto v4 = std::vector<int>{ 2,3,1 };

    std::cout << included(v3, v4) << '\n';
}

Demo on ideone.com

注意:我偷了Jarod42的函数名和coincoin的测试数据。