Cpp find element in vector

C++ : How to find an element in vector and get its index ?

In this article we will different ways to find an element in vector and get its index.

Suppose we have a vector of int i.e.

Now we want to find if number 22 exists in vector ? If yes then what’s its index or position in the vector ?

std::vector doesn’t provides any direct function to check if an element exists in vector or not. So let’s see how to do that using STL Algorithms.

Frequently Asked:

Finding an element in vector using STL Algorithm std::find()

Basically we need to iterate over all the elements of vector and check if given elements exists or not.
This can be done in a single line using std::find i.e.

// Check if element 22 exists in vector std::vector::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);

It accepts a range and an element to search in the given range. If element is found then it returns an iterator to the first element in the given range that’s equal to given element, else it returns an end of the list.

Читайте также:  User dir user home java

Are you a C++ programmer eager to step up your game?

Master the intricacies of C++/C++11/C++20 with our handpicked list of the Best Courses to Learn Modern C++11, C++17 and C++20. Sharpen your skills, conquer complex algorithms, and stand out in your professional or academic sphere.

This isn’t just about learning — it’s about transforming into the programmer you aspire to be. So, why wait?

Your leap towards programming excellence is just a click away.

if (it != vecOfNums.end()) std::cout 

If element is found then we can get its index from the iterator i.e.

// Get index of element from iterator int index = std::distance(vecOfNums.begin(), it);

But in practical, we will not have vector of integers always. So, let’s create a generic function for this.

Generic function to find an element in vector of any type

Let’s create a generic function to search an element in any type of vector i.e.

/* Generic function to find an element in vector and also its position. It returns a pair of bool & int i.e. bool : Represents if element is present in vector or not. int : Represents the index of element in vector if its found else -1 */ template < typename T>std::pair findInVector(const std::vector & vecOfElements, const T & element) < std::pairresult; // Find given element in vector auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element); if (it != vecOfElements.end()) < result.second = distance(vecOfElements.begin(), it); result.first = true; >else < result.first = false; result.second = -1; >return result; >

This function tells if given element exists in vector and if yes then it also return its position in the vector.

Let’s use this function to find an element in vector i.e.

std::pair result = findInVector(vecOfNums, 45); if (result.first) std::cout 

Finding an element by custom comparator using std::find_if()

Instead of directly searching by value in the vector , we can search by custom logic too.

Like, in a vector of int check if any multiple of 3 exists i.e.

// Check if any multiple of 3 exists in vector using lambda function as comparator std::vector::iterator it2 = std::find_if(vecOfNums.begin(), vecOfNums.end(), [](const int & val)< if (val % 3 == 0) return true; return false; >); if (it != vecOfNums.end()) std::cout 

Finding an element in vector using C++11 Range Based for loop

We can also iterate over the vector using range based for loop and check if element exists or not.

bool found = false; // Iterate over all elements in Vector for (auto & elem : vecOfNums) < if (elem == 22) < found = true; break; >> if(found) std::cout 

Complete example is as follows,

#include #include #include /* Generic function to find an element in vector and also its position. It returns a pair of bool & int i.e. bool : Represents if element is present in vector or not. int : Represents the index of element in vector if its found else -1 */ template < typename T>std::pair findInVector(const std::vector & vecOfElements, const T & element) < std::pairresult; // Find given element in vector auto it = std::find(vecOfElements.begin(), vecOfElements.end(), element); if (it != vecOfElements.end()) < result.second = distance(vecOfElements.begin(), it); result.first = true; >else < result.first = false; result.second = -1; >return result; > int main() < std::vectorvecOfNums = < 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 >; /* Find an element in vector using std::find */ // Check if element 22 exists in vector std::vector::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22); if (it != vecOfNums.end()) < std::cout else < std::cout std::pair result = findInVector(vecOfNums, 45); if (result.first) std::cout << "Element Found at index : " << result.second <); if (it != vecOfNums.end()) std::cout > if(found) std::cout

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

C++ Find Element in Vector

C++ Find Element in Vector

C++ provides the functionality to find an element in the given range of elements in a vector. This is done by the find() function which basically returns an iterator to the first element in the range of vector elements [first, last) on comparing the elements equals to the val (value to be searched). If the val to be searched is not found in the range, the function returns last. The best part about this function is that it stops searching and traversing the whole range as soon as the first occurrence of an element to be searched is found in the list.

Web development, programming languages, Software testing & others

Below given is the basic syntax of using the find() function to search the element in vector:

InputIterator(InputIterator first, InputIterator last, val_search)
  • first: the first/ initial position of the element in the range of vector sequence [first, last).
  • last: the last/ final position of the element in the range of vector sequence [first, last).
  • val_search: the value to be searched in the range of vector sequence.
  • Return value: It returns an iterator to the ‘first’ occurrence of the element if it is found in the range [first, last) and ‘last’ if the element is not found in the sequence.

Note: C++ find() function uses the == operator in order to compare the elements with the value ‘val’ to be searched.

How to Find Element in Vector in C++?

As already discussed, the find() function is used to find the elements in the vector in C++, which finds the very first occurrence of the element in the sequence having a linear time complexity. It takes 3 arguments as input, i.e. first, last, and the element which needs to be searched. Mentioned below are the sequence of steps that are followed to find the element in vector:

  • It starts from the initial position of the element in the range.
  • Compare each element using == operator with the value ‘val’ of the element given by the programmer and iterate further using the loop till the last.
  • Once the first occurrence of the element is found, it stops its execution and returns the iterator pointing to it.
  • Otherwise it returns ‘last’ if the element is not found in the sequence.

Examples to Implement C++ Find Element in Vector

Let us make things more clear with the help of C++ examples:

Example #1

Using to find() function just to check whether the element is present or not.

#include #include #include using namespace std; intmain() < // Initializing the vector elements vectorvec = < 100, 200, 300, 400, 500, 600, 700 >; //Inputting the element to be searched in vector intsearch_element = 500; //creating an iterator ‘it’ to store the result vector::iterator it; //using the find() function and storing the result in iterator ‘it’ it = find(vec.begin(), vec.end(), search_element); //checking the condition based on the ‘it’ result whether the element is present or not if (it != vec.end()) cout

C++ Find Element in Vector-1.1

Explanation: In the above example, we have used the 3 header files for different purposes, i.e. iostream for std: :cout, vector for std : :vector, and algorithm for std : :find. Vector ‘vec’ is initialized to its elements and the element to be searched is given in the variable ‘search_element’. Iteratot ‘it’ is used to store the result of the find() function. find () function is provided with its 3 parameters, i.e. first, last position of the element, and the element to be searched. Then the find() function condition is checked using the if and else statement. If the value held by ‘it’ is not equal to the position of ‘last’ element, then the element is found in the sequence otherwise not.

Example #2

Using the find() function to search the element and find its index in vector.

#include #include #include using namespace std; int main () < //Initializing the vector elements vectorvec_1 < 23, 10, 40, 54, 67, 98, 100 >; // Inputting the Element that is to be searched in vector intval = 54; // Printing the original vector elements cout else cout

C++ Find Element in Vector-1.2

Explanation: In the above code, vector ‘vec_1’ of integer type is initialized with the values in it. Element to be searched is stored in the variable ‘val’. First, all the vector elements are printed on the console using the ‘for’ loop. Basic functions like vec_1.size(), vec_1.begin(), vec_1,end() functions are used to find the size of vector, initial position and final position of element in vector.find() function is used providing all the 3 parameters, i.e. initial position, final position, and the element to be searched. The result is stored in an iterator ‘res’ which is then checked against the find() function condition. If its value is not equal to the final vector position, then the element is found in the vector, else the element is not found in the vector sequence.

An important thing to note in the program is finding the index of the element searched. As the variable ‘res’ holds the index of the first occurence of the element found, it is subtracted from ‘vec_1.begin(), which is the position of the first element in the vector ‘vec_1’. As the index starts from 0, 1 is added at the last to display the exact position according to the user’s viewpoint.

Conclusion

The above description clearly explains the find() function and how to use it in the C++ vector program to search an element in the sequence. std : : count is also used for the same purpose but std::find is considered to be the most efficient one as count is used to traverse the whole list whereas find stops once the element is found. C++ also offers functions like std : : find_if, std : :none_of, etc which are used for specific purposes to find the elements in a sequence.

This is a guide to C++ Find Element in Vector. Here we discuss the definition and how to find element in vector in c++? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

502+ Hours of HD Videos
54 Courses
4 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

57+ Hours of HD Videos
15 Courses
9 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Оцените статью