📜  在 C++ STL 中使用 binary_search()函数搜索字符串(1)

📅  最后修改于: 2023-12-03 15:37:18.459000             🧑  作者: Mango

在 C++ STL 中使用 binary_search() 函数搜索字符串

在 C++ STL(Standard Template Library)中,有一个很有用的函数叫做 binary_search(),它可以用来在一个已排序的序列中查找指定元素。这个函数的使用方法非常简单,我们只需要提供要搜索的序列和要查找的元素,就可以得到搜索结果。

本文将介绍如何在 C++ STL 中使用 binary_search() 函数来搜索字符串。我们将首先介绍 binary_search() 函数的用法,然后演示如何将其应用到字符串搜索中。

binary_search() 函数用法

binary_search() 函数的原型如下:

template <class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T &val);

其中,ForwardIterator 是正向迭代器类型,用来指定搜索范围的首尾指针;T 是要查找的元素类型;返回值是一个布尔类型,表示指定元素是否存在于指定序列中。

使用 binary_search() 函数进行搜索的过程如下:

  1. 首先对序列进行排序。
  2. 调用 binary_search() 函数,并指定搜索范围和要查找的元素。
  3. 如果函数返回 true,表示指定元素存在于指定序列中;否则表示不存在。

下面是一个例子,演示如何使用 binary_search() 函数来搜索一个 vector 中是否包含指定元素:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  std::vector<int> vec {1, 2, 3, 4, 5};

  if (std::binary_search(vec.begin(), vec.end(), 3)) {
    std::cout << "Found!" << std::endl;
  } else {
    std::cout << "Not found." << std::endl;
  }

  return 0;
}

输出结果为:

Found!

此处我们查找的是一个整数,但实际上 binary_search() 函数对类型没有限制,可以用来搜索任何已排序的序列。

使用 binary_search() 函数搜索字符串

下面我们将演示如何使用 binary_search() 函数来搜索字符串。

首先我们需要将字符串按照字典序进行排序,这可以通过 std::sort() 函数来完成,具体方法如下:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
  std::string str = "abcde";
  std::sort(str.begin(), str.end());

  std::cout << str << std::endl;

  return 0;
}

输出结果为:

abcde

现在我们已经将字符串进行了排序。接下来,我们可以使用 binary_search() 函数来查找指定的字符是否存在于字符串中,具体方法如下:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
  std::string str = "abcde";
  std::sort(str.begin(), str.end());

  char ch = 'b';
  if (std::binary_search(str.begin(), str.end(), ch)) {
    std::cout << ch << " found in string." << std::endl;
  } else {
    std::cout << ch << " not found in string." << std::endl;
  }

  return 0;
}

输出结果为:

b found in string.

此处我们查找了字符 'b' 是否存在于字符串中,而且由于字符串已经按照字典序排序,所以我们可以保证查找的正确性。

总之,使用 binary_search() 函数来搜索字符串是非常方便的,只需要先将字符串按照字典序排序,然后就可以使用 binary_search() 函数来查找指定字符是否存在于字符串中。