How do I find items in std::vector?

Asked 1 years ago, Updated 1 years ago, 62 views

I want to find out if there's an element in the vector How do we figure it out? How can I create item_present in the code below?

if ( item_present )
   do_this();
else
   do that();

c++ vector std

2022-09-21 20:23

1 Answers

Write std::find in <algorithm>

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

You can use it with this Returns true if the item exists, and false if it does not exist.

I'll attach a simple example

#include <algorithm>

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


2022-09-21 20:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.