【发布时间】:2018-09-01 15:41:47
【问题描述】:
我正在尝试编写一个程序来检查一个向量的内容是否存在于另一个向量中。例如:
vector<int> a = {1, 2};
vector<int> b = {6, 5, 3, 1, 9, 2};
比较这两个向量时返回 true,因为 a 的内容存在于 b 的某个位置。
vector<int> a = {1, 2}
vector<int> b = {3, 1, 5, 6}
这将返回 false,因为 a 中的 所有内容 都不存在于 b 中。
我已经尝试过使用while 循环,但我不知道如何让循环中断。
bool check_vec(vector<int> a, vector<int> b){
int checker = 0;
int i = 0;
int q = 0;
while ( true ) {
if(b.at(i) == a.at(q)) {
checker++;
i = 0;
q++;
if(checker == a.size())
return true;
i++;
}
}
}
【问题讨论】:
-
那甚至无法编译。发布minimal reproducible example。
-
至少,您至少缺少两个右括号
-
为什么第一个例子会返回true?
a中的2在b中不存在。在任何情况下,您都应该通过vector<int>&参考来获取输入向量。如果先对向量进行排序然后检查b是否以与a相同的值开头,则搜索可能会更容易。或者使用std::includes()或std::set_intersection()而不是手动搜索