21xrx.com
2024-09-20 06:08:24 Friday
登录
文章检索 我的文章 写文章
C++中的set容器查找方法
2023-07-12 12:07:38 深夜i     --     --
C++ set容器 查找方法

在C++语言中,set是一种容器,它可以存储一组有序的、不重复的元素。set中的元素是按照从小到大的顺序排列的,因此在查找set中的元素时可以直接使用set容器提供的查找方法。

set容器中提供了两种查找元素的方法:find()和count()。其中,find()方法用于查找并返回set容器中指定的元素,如果找到了,则返回一个指向该元素的迭代器;如果没有找到,则返回set中的尾迭代器。例如:


#include <iostream>

#include <set>

using namespace std;

int main() {

  set<int> s = 1;

  auto it = s.find(3);

  if (it != s.end())

    cout << "Found " << *it << " in s." << endl;

  else

    cout << "3 is not in s." << endl;

  return 0;

}

上述代码中,首先创建了一个set容器,然后调用find()方法查找元素3。如果找到了元素3,则输出“Found 3 in s.”;否则输出“3 is not in s.”。在本例中,set容器中确实存在元素3,因此输出“Found 3 in s。”。

与find()方法类似,count()方法也可以用于查找set容器中的元素。不同的是,count()方法返回的是指定元素在set中的出现次数,因此它返回的是一个整数值。如果指定的元素在set中不存在,则返回零。例如:


#include <iostream>

#include <set>

using namespace std;

int main() {

  set<int> s = 4;

  int cnt = s.count(3);

  if (cnt == 1)

    cout << "3 is in s." << endl;

  else

    cout << "3 is not in s." << endl;

  return 0;

}

上述代码中,首先创建了一个set容器,然后调用count()方法查找元素3。如果找到了元素3,则输出“3 is in s.”;否则输出“3 is not in s.”。在本例中,set容器中确实存在元素3,因此输出“3 is in s.”。

总的来说,set容器提供了简单、高效的查找元素方法。程序员可以根据实际需求选择使用find()方法还是count()方法。需要注意的是,使用count()方法时返回的是某个元素在set中的个数,因此如果只是查找某个元素是否存在,建议使用find()方法。

  
  

评论区

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