如何找到一个项目是否存在于std :: vector? [英] How to find if an item is present in a std::vector?

查看:131
本文介绍了如何找到一个项目是否存在于std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有我想要做的是检查一个元素是否存在于向量中,所以我可以处理每种情况。

All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.

if ( item_present )
   do_this();
else
   do_that();


推荐答案

您可以使用

You can use std::find from <algorithm>:

std::find(vector.begin(), vector.end(), item) != vector.end()

这会返回一个bool( true 如果存在, false 否则)。以您的示例:

This returns a bool (true if present, false otherwise). With your example:

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   do_this();
else
   do that();

这篇关于如何找到一个项目是否存在于std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆