我需要编写一个程序来找出两个 vector 之一是否包含在另一个 vector 中。 该程序的工作原理如下。
1 - 从 input.txt
(第一行)获取 m
和 n
值
2 - 将 verctorM
和 vectorN
调整为 m
和 n
,然后用 中的数字填充它们>input.txt
(第 2 行为 vectorM
,第 3 行为 vectorN
)
3 - 填充后,程序应通过比较 n
和 m
4 - 程序获取“小” vector 的第一个“字符”,并开始将其与“大” vector 的“字符”进行比较 ()
5 - 当语句 vectorN[i] = vectorM[0]
正确时,如果“小” vector 的每个“字符”都在“大” vector 中,则程序将比较下一个“字符” "vector ,程序输出1
,如果没有则继续与"smal"vector 的第一个"字符"进行比较,如果"small"vector 不包含在"big"vector 中,程序输出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;
}
比较“字符”的有效方法是什么??
示例,如果在 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
最佳答案
我认为您是在问是否可以在另一个值范围内找到连续的子序列。标准库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';
}
注意:我窃取了Jarod42的函数名称和coincoin的测试数据。
关于c++ - 查找 1 个 vector 是否包含在第 2 个 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255605/