Click here to Skip to main content
15,878,543 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
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:

Google, Documentation, wiki upon wiki.
Posted
Updated 14-Aug-23 1:07am

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.
 
Share this answer
 
v2
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...
        }
    }
    return false; //Element not found,...
}

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.
Element 6 not found in the vector
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900