Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 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 Reply

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...