21xrx.com
2025-03-27 18:50:59 Thursday
文章检索 我的文章 写文章
C++中的向量(vector)的查找用法
2023-06-25 22:00:24 深夜i     17     0
C++ 向量 vector 查找 用法

C++是一门广泛应用的编程语言,其中向量(vector)是一种常用的数据结构类型。在C++中,向量通常用于存储可变长度的序列数据,如字符串、数组等,同时向量也提供了一系列方便的方法用于查找。

向量的查找方法主要有两种,即通过迭代器遍历查找和使用STL库中的查找函数。下面将具体介绍这两种方法的使用。

首先是通过迭代器遍历查找。操作步骤如下:

1.通过begin()和end()方法获得向量的首位迭代器。

2.通过使用迭代器,遍历整个向量。

3.对于每个元素进行判断,如果满足需要查找的条件,则返回该元素的位置。

4.如果向量中不存在要查找的元素,则返回不存在的信息。

下面是一个简单的示例代码:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
  vector<int> vec = 5;
  int find_num = 3;
  
  auto it = vec.begin();
  for (; it != vec.end(); it++)
  {
    if (*it == find_num)
    {
      cout << "The number " << find_num << "is at position " << (it - vec.begin()) << endl;
      break;
    }
  }
  
  if (it == vec.end())
  
    cout << "The number is not found" << endl;
  
  
  return 0;
}

其次是使用STL库中的查找函数。在STL库中,提供了多个向量查找函数,包括find,count,find_if和count_if等等。这些函数使用方法类似,与通过迭代器遍历查找有一定相似性。这里以find()函数为例,简单介绍一下其使用方法。

find()函数接收两个迭代器参数,表示查找区间的起始点和结束点,同时还接收一个要查找的值的参数,并在该区间内查找该值。如果找到了,函数返回该元素的位置,否则返回end()迭代器。下面是一个简单的示例代码:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
  vector<int> vec = 1;
  int find_num = 3;
  auto it = find(vec.begin(), vec.end(), find_num);
  
  if (it != vec.end())
  {
    cout << "The number " << find_num << "is at position " << (it - vec.begin()) << endl;
  }
  else
  
    cout << "The number is not found" << endl;
  
  
  return 0;
}

综上所述,通过迭代器遍历查找和使用STL库中的查找函数是向量的两种主要查找方法。可以根据不同的需要,选择合适的方法用于查找向量中的数据。

  
  

评论区