21xrx.com
2024-05-20 14:06:59 Monday
登录
文章检索 我的文章 写文章
C++ 如何判断某个元素是否存在?
2023-07-13 10:26:44 深夜i     --     --
C++ 判断 元素 存在

在C++中,我们可以用多种方法来判断某个元素是否存在。下面将介绍常见的两种方法。

一、使用find()函数

C++中STL库中有一个非常方便的函数——find()函数,它可以用于查找某个元素是否在指定范围内存在。

find()函数的函数原型为:


template<class InputIterator, class T>

InputIterator find (InputIterator first, InputIterator last, const T& value);

其中,参数first和last分别为指向首元素和尾元素的迭代器,而value就是需要查找的元素值。

具体使用方法如下:


#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main()

{

  vector<int> vec = 2;

  int x = 3;

  if(find(vec.begin(), vec.end(), x) != vec.end())

    cout << "元素存在" << endl;

  else

    cout << "元素不存在" << endl;

  return 0;

}

这里我们声明了一个vector vec,并用 4来初始化。接着,定义了一个整型变量x,并赋值为3。

在使用find()函数时,我们首先输入需要查找的范围——vec.begin()和vec.end(),然后再输入需要查找的元素值——x,最后通过判断返回值是否等于vec.end()来判断元素是否存在。

Execute结果:


元素存在

二、使用count()函数

除了find()函数,STL库中还提供了另一个函数——count()函数。顾名思义,该函数是用来计算某个元素在指定范围内出现的次数。

count()函数的函数原型为:


template<class InputIterator, class T>

typename iterator_traits<InputIterator>::difference_type count(InputIterator first, InputIterator last, const T& value);

其中,first和last同样是指向首元素和尾元素的迭代器,而value就是需要计算出现次数的元素值。返回值类型为迭代器difference_type。

具体使用方法如下:


#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int main()

{

  vector<int> vec = 3;

  int x = 3;

  if(count(vec.begin(), vec.end(), x))

    cout << "元素存在" << endl;

  else

    cout << "元素不存在" << endl;

  return 0;

}

这里我们同样使用了vector vec,将其初始化为1。在count()函数中,我们传入了vec.begin()和vec.end(),以及需要计数的元素值x。

这里需要说明的是,如果所查找的元素存在于指定容器中,则count()函数将返回非零值,否则返回0。

Execute结果:


元素存在

以上就是C++中判断某个元素是否存在的两种方法。不管使用哪种方法,只要返回结果为非零值,则表示指定元素在指定范围内存在。

  
  

评论区

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