【发布时间】:2015-12-11 12:52:04
【问题描述】:
我正在学习入门级 C++ 课程。我必须编写一个布尔函数来检查向量中的重复项,如果没有重复项,则返回 true 和 false
#include<iostream>
#include<vector>
using namespace std;
bool has_duplicates(const vector <int> &v);
int main() {
vector<int> Vec(8);
Vec = { 20, 30, 40, 50, 10, 20, 5, 6 };
has_duplicates(Vec);
return 0;
}
bool has_duplicates(const vector<int>& v) {
bool duplicatefound = false;
for (int i = 0; i < 8; i++) { // Check each other number in the array
for (int j = i; j < 8; j++) { // Check the rest of the numbers
while (j != i) {// Makes sure don't check number against itself
if (v[i] == v[j]) {
cout << "duplicate found" << endl;
duplicatefound = true;
break;
}
}
}
}
return duplicatefound; // Reset the boolean after each number entered has been checked
}
【问题讨论】:
-
你能告诉我你尝试过的事情吗?我们想帮助你。但我们不是从 0 开始。分享你的想法。
-
Stack Overflow 是一个问答网站。您的Q问题是什么?
-
首先开始创建一个包含一些重复值的数组。然后循环遍历数组。在上一个循环中尝试创建另一个循环,并寻找一种在发现重复值时返回 true 的方法
-
你有一个问题(减去语法错误)你允许 i 等于 j 在下面的
if (v[i] == v[j]) {这将使 has_duplicates 总是返回 true。
标签: c++