C++ || How To Check If An Item Exists In A Vector And Get Its Position Index Using C++
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Contains // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { std::cout << "Name: " << name << ", Contains Item: " << (Utils::contains(names, name) ? "True" : "False") << std::endl; } // expected output: /* Name: Lynn, Contains Item: True Name: Jessica, Contains Item: False */ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Index Of // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { std::cout << "Name: " << name << ", Index: " << Utils::indexOf(names, name) << std::endl; } // expected output: /* Name: Lynn, Index: 2 Name: Jessica, Index: -1 */ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Index Of - Predicate // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { auto pred = [name](const auto& x) { return x == name; }; std::cout << "Name: " << name << ", Index: " << Utils::indexOf(names, pred) << std::endl; } // expected output: /* Name: Lynn, Index: 2 Name: Jessica, Index: -1 */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <algorithm> #include <iterator> namespace Utils { /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value in * the given range [first, last) * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename InputIt, typename Pred> int indexOf(InputIt first, InputIt last, const Pred& predicate) { auto pos = std::find_if(first, last, predicate); return pos != last ? pos - first : -1; } /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value * in the collection * @param source: The collection to find items * @param predicate: A function to test each element for a condition * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename T, typename Pred> int indexOf(const std::vector<T>& source, const Pred& predicate) { return indexOf(source.begin(), source.end(), predicate); } /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value * in the collection * @param source: The collection to search * @param search: The item to search for * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename T> int indexOf(const std::vector<T>& source, const T& search) { auto pred = [&](const T& x) { return x == search; }; return indexOf(source, pred); } /** * FUNCTION: contains * USE: Determines whether an element is in the given range [first, last) * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: True if the item is inside the collection, false otherwise */ template<typename InputIt, typename Pred> bool contains(InputIt first, InputIt last, const Pred& predicate) { return indexOf(first, last, predicate) > -1; } /** * FUNCTION: contains * USE: Determines whether an element is in the collection * @param source: The collection to search * @param predicate: A function to test each element for a condition * @return: True if the item is inside the collection, false otherwise */ template<typename InputIt, typename T = typename std::iterator_traits<InputIt>::value_type, typename Pred> bool contains(const std::vector<T>& source, const Pred& predicate) { return indexOf(source.begin(), source.end(), predicate) > -1; } /** * FUNCTION: contains * USE: Determines whether an element is in the collection * @param source: The collection to search * @param search: The item to search for * @return: True if the item is inside the collection, false otherwise */ template<typename T> bool contains(const std::vector<T>& source, const T& search) { return indexOf(source, search) > -1; } }// http://programmingnotes.org/ |
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!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { display("Name: " + name + ", Contains Item: " + (Utils::contains(names, name) ? "True" : "False")); } // Display results for (const auto& name : searches) { display("Name: " + name + ", Index: " + std::to_string(Utils::indexOf(names, name))); } // Display results for (const auto& name : searches) { auto pred = [name](const auto& x) { return x == name; }; display("Name: " + name + ", Index: " + std::to_string(Utils::indexOf(names, pred))); } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
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