C++ || How To Check If An Item Exists In A Vector And Get Its Position Index Using C++

Print Friendly, PDF & Email

The following is a module with functions which demonstrates how to find the position index of an item in a vector, and make sure the item exists using C++.

The functions demonstrated on this page are wrappers for std::find_if function, and are templates, so they should work on vectors/containers of any type.


1. Contains

The example below demonstrates the use of ‘Utils::contains‘ to determine whether an element is contained in the collection.


2. Index Of

The example below demonstrates the use of ‘Utils::indexOf‘ to get the zero based index of the first occurrence of a search value in the collection.


3. Index Of – Predicate

The example below demonstrates the use of ‘Utils::indexOf‘ to get the zero based index of the first occurrence of a search value in the collection.

In this example, a predicate is used to determine the item to search for. This allows you to customize how an item should be searched.


4. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


5. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Leave a Reply