Wednesday, January 15, 2025
HomeProgrammingHow to find out if an item is present in a std::vector?

How to find out if an item is present in a std::vector?

To check if an item exists in a std::vector, use std::find from the header. Below is the code:

#include
#include
#include

int main() {
std::vector vec = {1, 2, 3, 4, 5};
int item = 3;

auto it = std::find(vec.begin(), vec.end(), item);
if (it != vec.end()) {
std::cout << "Item found at index: " << std::distance(vec.begin(), it) << std::endl; } else { std::cout << "Item not found" << std::endl; }

See also  What is the Difference between Public, Protected, Package Private, and Private in Java
return 0; } This code checks for item in vec. If found, it prints the index; otherwise, it shows "Item not found."

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x