Daily Archives: December 7, 2020
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.
C++ || How To Merge & Concatenate Two Vectors Using C++
The following is a module with functions which demonstrates how to merge, concatenate and append two vectors using C++.
The function demonstrated on this page is a template, so it should work on vectors of any type.
1. Add Range
The example below demonstrates the use of ‘Utils::addRange‘ add elements to the end of the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Add Range // Declare vector std::vector<std::string> names = {"Kenneth"}; // Add more names Utils::addRange(names, {"Jennifer", "Lynn", "Sole"}); // Display results for (const auto& name : names) { std::cout << "Name: " + name << std::endl; } // expected output: /* Name: Kenneth Name: Jennifer Name: Lynn Name: Sole */ |
2. 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 |
// ============================================================================ // 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 <iterator> namespace Utils { /** * FUNCTION: addRange * USE: Adds elements to the end of the collection * @param source: The collection that will have items added to it * @param addition: The items that should be added to the end of the collection * @return: N/A */ template<typename T> void addRange(std::vector<T>& source, const std::vector<T>& addition) { source.reserve(source.size() + addition.size()); source.insert(source.end() , std::make_move_iterator(addition.begin()) , std::make_move_iterator(addition.end())); } }// http://programmingnotes.org/ |
3. 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 |
// ============================================================================ // 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"}; // Add more names Utils::addRange(names, {"Jennifer", "Lynn", "Sole"}); // Display results for (const auto& name : names) { display("Name: " + name); } } 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.
C++ || How To Replace All Occurrences Of A String With Another String Using C++
The following is a module with functions which demonstrates how to replace all occurrences of a substring with another substring using C++.
1. Replace All
The example below demonstrates the use of ‘Utils::replaceAll‘ to replace all occurrences of an ‘oldValue’ string with a ‘newValue’ string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Replace All // Declare string std::string numbers = "1987 19 22 2009 2019 1991 28 31"; // Replace whitespace with a comma std::string replaced = Utils::replaceAll(numbers, " ", ", "); // Display the result std::cout << "Original: " << numbers; std::cout << "Replaced: " << replaced; // expected output: /* Original: 1987 19 22 2009 2019 1991 28 31 Replaced: 1987, 19, 22, 2009, 2019, 1991, 28, 31 */ |
2. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> namespace Utils { /** * FUNCTION: replaceAll * USE: Replaces all occurrences of the 'oldValue' string with the * 'newValue' string * @param source: The source string * @param oldValue: The string to be replaced * @param newValue: The string to replace all occurrences of oldValue * @return: A new string with all occurrences replaced */ std::string replaceAll(const std::string& source , const std::string& oldValue, const std::string& newValue) { if (oldValue.empty()) { return source; } std::string newString; newString.reserve(source.length()); std::size_t lastPos = 0; std::size_t findPos; while (std::string::npos != (findPos = source.find(oldValue, lastPos))) { newString.append(source, lastPos, findPos - lastPos); newString += newValue; lastPos = findPos + oldValue.length(); } newString += source.substr(lastPos); return newString; } }// http://programmingnotes.org/ |
3. 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 |
// ============================================================================ // 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 "Utils.h" void display(const std::string& message); int main() { try { // Declare string std::string numbers = "1987 19 22 2009 2019 1991 28 31"; // Replace whitespace with a comma std::string replaced = Utils::replaceAll(numbers, " ", ", "); // Display the result display("Original: " + numbers); display("Replaced: " + replaced); } 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.