Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

c++ - 如何找出std :: vector中是否存在项目?(How to find out if an item is present in a 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();
  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(您可以从<algorithm>使用std::find :)

#include <vector>
vector<int> vec; 
//can have other data types instead of int but must same datatype as item 
std::find(vec.begin(), vec.end(), item) != vec.end()

This returns a bool ( true if present, false otherwise).

(这将返回一个布尔值(如果存在则为true ,否则为false )。)

With your example:

(以您的示例为例:)

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...