15,994,072 members
See more:
This is kind of a problem since I try this with functions and templates but I figure I may as well take any advice and help those with more experience can give me. So how would I be able to make a function or class to find an element in a vector? Any help given is appreciated!

What I have tried:

Posted
Updated 14-Aug-23 1:07am

## Solution 1

You could use std::find: How to find out if an item is present in a std::vector?[^]

A very quick google would have got you that half an hour ago ... I searched for "vector.find c++" and it was the top hit.

v2

## Solution 2

Google is your friend, not sure what you searched for. I found this link with sample code - C++ Find Element in Vector[^]

Your code will look something like -
C++
```#include <iostream>
#include <vector>

// Function to find an element in a vector
template <typename T>
bool findElementInVector(const std::vector<T>& vec, const T& element) {
//Iterate through the vector...
for (const T& item : vec) {
//Check if the current element matches the target element...
if (item == element) {
return true; //Element found, all good...
}
}
}

int main() {
// Example usage
std::vector<int> numbers = {1, 2, 3, 4, 5};

int target = 3;
if (findElementInVector(numbers, target)) {
std::cout << "Element " << target << " found in the vector." << std::endl;
} else {
std::cout << "Element " << target << " not found in the vector." << std::endl;
}

target = 6;
if (findElementInVector(numbers, target)) {
std::cout << "Element " << target << " found in the vector." << std::endl;
} else {
std::cout << "Element " << target << " not found in the vector." << std::endl;
}

return 0;
}```

Using an online compiler like -
C++ Online Compiler
[^], I get an output of -
Output
```Element 3 found in the vector.