21xrx.com
2025-03-28 03:31:11 Friday
文章检索 我的文章 写文章
C++ 数据查找代码
2023-07-05 10:42:39 深夜i     16     0
C++ 数据查找 代码

C++是一种流行的编程语言,用于开发各种类型的应用程序。其中之一就是数据查找,C++提供了许多函数和类来帮助开发人员进行数据查找操作。以下是一些C++数据查找代码的示例:

1. 顺序查找

顺序查找是最基本的查找算法之一。它是通过依次比较数组中的每个元素来查找特定元素的。以下是一个使用顺序查找来查找给定值的示例代码:

#include <iostream>
using namespace std;
int main()
{
  int arr[5] = 20;
  int n = sizeof(arr)/sizeof(arr[0]);
  int x = 30;
  int i;
  for (i = 0; i < n; i++)
  {
    if (arr[i] == x)
    {
      cout << "元素在位置 " << i + 1;
      break;
    }
  }
  if (i == n)
    cout << "元素未找到" << endl;
  return 0;
}

2. 二分查找

二分查找也称为折半查找,它是一种更快的搜索算法。该算法要求在有序集合中查找值的位置,并且它适用于较大的数据集。以下是一个使用二分查找来查找给定值的示例代码:

#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
  if (r >= l) {
    int mid = l + (r - l) / 2;
    if (arr[mid] == x)
      return mid;
    if (arr[mid] > x)
      return binarySearch(arr, l, mid - 1, x);
    return binarySearch(arr, mid + 1, r, x);
  }
  return -1;
}
int main()
{
  int arr[] = 9 ;
  int n = sizeof(arr) / sizeof(arr[0]);
  int x = 7;
  int result = binarySearch(arr, 0, n - 1, x);
  (result == -1) ? cout << "元素未找到"
          : cout << "元素在位置 " << result + 1;
  return 0;
}

3. 散列表查找

散列表是一种支持在常量时间内进行插入和查找的算法。这种算法通过哈希函数将元素映射到地址空间中的某个位置。然后,查找元素时可以使用相同的哈希函数来确定元素的位置。以下是一个使用散列表查找给定值的示例代码:

#include <iostream>
#include <list>
#include <iterator>
using namespace std;
class HashTable
{
  int bucket;
  list<int>* table;
public:
  HashTable(int V);
  void insertItem(int key, int data);
  void deleteItem(int key);
  int hashFunction(int x)
  {
    return (x % bucket);
  }
  void displayHash();
};
HashTable::HashTable(int b)
{
  this->bucket = b;
  table = new list<int>[bucket];
}
void HashTable::insertItem(int key, int data)
{
  int index = hashFunction(key);
  table[index].push_back(data);
}
void HashTable::deleteItem(int key)
{
  int index = hashFunction(key);
  list<int>::iterator i;
  for (i = table[index].begin();
     i != table[index].end(); i++) {
    if (*i == key)
      break;
  }
  if (i != table[index].end())
    table[index].erase(i);
}
void HashTable::displayHash()
{
  for (int i = 0; i < bucket; i++) {
    cout << i;
    for (auto x : table[i])
      cout << " --> " << x;
    cout << endl;
  }
}
int main()
{
  int a[] = {15, 11, 27, 8, 12};
  int n = sizeof(a)/sizeof(a[0]);
  HashTable h(7);
  for (int i = 0; i < n; i++)
    h.insertItem(a[i], a[i]);
  h.deleteItem(12);
  h.displayHash();
  return 0;
}

以上是一些常见的C++数据查找代码示例。在实际开发中,程序员可以根据实际需求选择使用最合适的算法,以获得最优的性能。

  
  

评论区

请求出错了