21xrx.com
2024-09-20 01:13:04 Friday
登录
文章检索 我的文章 写文章
C++中的find函数
2023-07-05 01:06:20 深夜i     --     --
C++ find函数 寻找

C++中,find()是一种用于在容器中查找元素的函数。该函数返回指向第一个匹配项的迭代器。如果没有找到匹配项,则返回指向末尾的迭代器。

find()函数可用于以下容器的搜索:

- 向量(vector)

- 列表(list)

- 集(set)

- 映射(map)

下面是一个使用向量和find()函数查找元素的示例:


#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main() {

  vector<int> vec = 20;

  int x = 30;

  auto it = find(vec.begin(), vec.end(), x);

  if (it != vec.end()) {

   cout << "元素 " << x << " 在向量中的位置为 " << it - vec.begin() << endl;

  }

  else

   cout << "元素 " << x << " 没有在向量中找到" << endl;

 

  return 0;

}

上面的代码演示了如何在向量中查找元素。在这种情况下,我们搜索整数30。如果找到,则输出元素的位置(即向量中的索引),否则输出未找到消息。

类似地,可以使用find()函数在其他容器中搜索元素。唯一的区别在于要将容器的起始和终止位置传递给该函数。

例如,在集合中查找元素的代码如下:


#include <iostream>

#include <set>

#include <algorithm>

using namespace std;

int main() {

  set<int> myset = 20;

  int x = 30;

  auto it = myset.find(x);

  if (it != myset.end())

   cout << "元素 " << x << " 在集合中找到" << endl;

 

  else

   cout << "元素 " << x << " 没有在集合中找到" << endl;

 

  return 0;

}

注意,对于集合,我们使用myset.find()代替std::find(),因为它是针对该容器定义的成员函数。

在C++中,find()函数是一种非常有用的函数。它可用于快速搜索容器中的元素,并可用于多种容器类型。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复