当前位置:首页 > IT技术 > 编程语言 > 正文

C++vector中如何查找某个元素是否存在?
2022-09-06 22:38:41

更普遍的讲,我们对于vector内元素的需求不同,因此操作也有差异

  1. std::binary_search
//先对vector进行排序,再使用二分查找,时间复杂度为O(logn)
//注意在C++中也有sort函数,与python不同的是,它需要两个参数,分别是vector的开头元素,和vector的结尾元素
sort(v.begin(), v.end());
//这里的key就是我们要确认是否存在于vector中的元素
if (std::binary_search(v.begin(), v.end(), key))
//若存在,返回true;不存在返回false
  1. std::find
    该方法优点是,找到目标元素后立即返回,很快!
#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;
using std::count;
using std::cout;
using std::endl;

int main()
{
		vector<int> v{ 4, 7, 9, 1, 2, 5 };
		int key = 2;
		
		if (std::find(v.begin(), v.end(), key) != v.end())
		{
				cout << "Element found" << endl;
		}
		else
		{
				cout << "Element NOT found" << endl;
		}
		
		return 0;
}

  1. std::cout
    与find相对应,cout是在遍历所有元素后才返回
    代码只需要将上述条件语句改为if (count(v.begin(), v.end(), key))即可

本文摘自 :https://www.cnblogs.com/