给定一个集合查找元素是否在集合中的c++代码
时间: 2024-05-12 21:15:31 浏览: 13
可以使用STL中的find函数来查找元素是否在集合中,示例代码如下:
```cpp
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s = {1, 3, 5, 7, 9};
int x;
cout << "Enter a number to search: ";
cin >> x;
// 使用find函数查找元素是否在集合中
if (s.find(x) != s.end()) {
cout << x << " is in the set." << endl;
} else {
cout << x << " is not in the set." << endl;
}
return 0;
}
```
运行结果:
```
Enter a number to search: 5
5 is in the set.
```
相关问题
用C++代码:使用模板类对给定的查找集合顺序查找与给定值k相等的元素,对给定的查找集合折半查找与给定值k相等的元素
顺序查找:
```c++
#include <iostream>
using namespace std;
template <class T>
int sequentialSearch(T arr[], int n, T key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
int index = sequentialSearch(arr, n, key);
if (index != -1) {
cout << "Element found at index " << index << endl;
} else {
cout << "Element not found" << endl;
}
return 0;
}
```
折半查找:
```c++
#include <iostream>
using namespace std;
template <class T>
int binarySearch(T arr[], int n, T key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
int index = binarySearch(arr, n, key);
if (index != -1) {
cout << "Element found at index " << index << endl;
} else {
cout << "Element not found" << endl;
}
return 0;
}
```
用C++写代码:用模板类对给定的查找集合顺序查找与给定值k相等的元素。 对给定的查找集合折半查找与给定值k相等的元素。
下面是用模板类实现顺序查找与折半查找的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class Search {
public:
static int seqSearch(vector<T>& arr, T key) {
for (int i = 0; i < arr.size(); i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
static int binarySearch(vector<T>& arr, T key) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
};
int main() {
vector<int> arr = {1, 3, 5, 7, 9};
int key = 5;
int index1 = Search<int>::seqSearch(arr, key);
int index2 = Search<int>::binarySearch(arr, key);
cout << "Sequential Search: " << index1 << endl;
cout << "Binary Search: " << index2 << endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个模板类 `Search`,其中包含两个静态函数 `seqSearch` 和 `binarySearch`,分别实现了顺序查找和折半查找。
在 `seqSearch` 函数中,我们使用一个循环来遍历整个数组,如果找到了目标元素,则返回其下标,否则返回 -1。
在 `binarySearch` 函数中,我们使用一个循环来不断缩小查找区间,直到找到目标元素或者查找区间为空。在每一次循环中,我们计算出中间位置 mid,如果中间位置的元素等于目标元素,则返回其下标;否则,如果中间位置的元素小于目标元素,则将查找区间左端点移到 mid + 1,否则将查找区间右端点移到 mid - 1。
最后,在 main 函数中,我们定义了一个整型数组和一个目标值,然后分别调用 `seqSearch` 和 `binarySearch` 函数来查找目标元素,输出它们的下标。