在 C++ STL 中使用 binary_search()函数搜索字符串
用于搜索给定字符串的内置 STL 库函数binary_search()是否存在于给定字符串数组中。二分搜索是一种分而治之的方法。二分搜索算法背后的想法是将数组一分为二,直到找到元素,或者所有元素都用尽。将数组的中间项与目标值即需要搜索的值进行比较,如果匹配则返回true,否则如果中间项大于目标,则在左子数组中进行搜索。如果中间项小于目标,则在右子数组中执行搜索。
例子:
Input: arr[] = {“Geeks”, “For”, “GeeksForGeek”}
Search “Geeks”
Output: String Founded in array
句法:
binary_search(starting_address, ending_address, value_of_string)
下面是上述方法的实现:
C++14
// C++ program to implement Binary
// Search in Standard Template Library (STL)
#include
#include
using namespace std;
void show_array(string arr[], int arraysize)
{
for (int i = 0; i < arraysize; i++)
cout << arr[i] << ", ";
}
void binarySearch(string arr[], int size)
{
cout << "\nThe array is : \n";
show_array(arr, size);
// Sort string array a for binary search as prerequisite
sort(arr, arr + size);
// Finding for "Geeks"
cout << "\n\nSearching Result for \"Geeks\"";
if (binary_search(arr, arr + size, "Geeks"))
cout << "\nString Founded in array\n";
else
cout << "\nString not Founded in array\n";
// Finding for string str
string str = "Best";
cout << "\nSearching Result for \"Best\"";
if (binary_search(arr, arr + size, str))
cout << "\nString Found in array";
else
cout << "\nString not Found in array";
}
// Driver code
int main()
{
// Initialising string array a
string arr[] = { "Geeks", "For", "GeeksForGeek" };
// Find size of array arr
int size = sizeof(arr) / sizeof(arr[0]);
// Function call
binarySearch(arr, size);
return 0;
}
输出:
The array is :
Geeks, For, GeeksForGeek,
Searching Result for "Geeks"
String Founded in array
Searching Result for "Best"
String not Found in array
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。