Daily Archives: December 8, 2020
C++ || How To Get A List Of Files At A Given Path Directory Using C++

The following is a module with functions which demonstrates how to get a list of files at a given directory path using C++.
The function demonstrated on this page returns a list of std::filesystem::directory_entry, which contains information about the files in the given directory.
1. Get Files In Directory
The example below demonstrates the use of ‘Utils::getFilesInDirectory‘ to get a list of files at a given path directory.
The optional function parameter lets you specify the search option. Set the search option to True to limit the search to just the current directory. Set the search option to False to expand the search to the current directory and all subdirectories when searching for files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Get Files In Directory // Declare path std::string directory = "C:\\Users\\Name\\Desktop"; // Get files at the specified directory auto files = Utils::getFilesInDirectory(directory); // Display info about the files for (const auto& file : files) { std::cout << "File: " << file.path().u8string() << std::endl; } // example output: /* File: C:\Users\Name\Desktop\text.txt File: C:\Users\Name\Desktop\image.png File: C:\Users\Name\Desktop\document.docx */ |
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 39 40 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <filesystem> namespace Utils { /** * FUNCTION: getFilesInDirectory * USE: Returns a 'directory_entry' list of the files in the given directory * @param directory: The relative or absolute path to the directory to search * @param topDirectoryOnly: If True, limits the search to just the current * directory. If False, expands the search to the current directory * and all subdirectories * @return: A list of 'directory_entry' in the given directory */ auto getFilesInDirectory(const std::string& directory, bool topDirectoryOnly = true) { namespace fs = std::filesystem; std::vector<fs::directory_entry> results; auto fill = [&results](const auto& iter) { for (const fs::directory_entry& entry : iter) { if (!entry.is_regular_file()) { continue; } results.push_back(entry); } }; if (topDirectoryOnly) { fill(fs::directory_iterator(directory)); } else { fill(fs::recursive_directory_iterator(directory)); } return results; } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 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 path std::string directory = "C:\\Users\\Name\\Desktop"; // Get files at the specified directory auto files = Utils::getFilesInDirectory(directory); // Display info about the files for (const auto& file : files) { std::cout << "File: " << file.path().u8string() << std::endl; } } 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 Make Map & Unordered Map Keys Case Insensitive Using C++

The following is a module with functions which demonstrates how to make map and unordered_map keys case insensitive using C++.
1. Case Insensitive – Map
The example below demonstrates how to make a map with a string key case insensitive.
To do this, the comparison function needs to be overridden.
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 |
// Case Insensitive - Map #include <string> #include <map> // Makes map keys case insensitive struct case_insensitive_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) < 0; } }; }; // Declare map std::map<std::string, unsigned, case_insensitive_map::comp> map = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << map["kenneth"] << ", " << map["JeNniFer"] << ", " << map["LYNN"] << ", " << map["sole"]; // expected output: /* 2019, 2010, 28, 31 */ |
2. Case Insensitive – Unordered Map
The example below demonstrates how to make an unordered map with a string key case insensitive.
To do this, the comparison and the hash function needs to be overridden.
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 |
// Case Insensitive - Unordered Map #include <string> #include <unordered_map> #include <utility> #include <cctype> // Makes unordered map keys case insensitive struct case_insensitive_unordered_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) == 0; } }; struct hash { std::size_t operator() (std::string str) const { for (std::size_t index = 0; index < str.size(); ++index) { auto ch = static_cast<unsigned char>(str[index]); str[index] = static_cast<unsigned char>(std::tolower(ch)); } return std::hash<std::string>{}(str); } }; }; // Declare unordered map std::unordered_map<std::string, unsigned , case_insensitive_unordered_map::hash , case_insensitive_unordered_map::comp> unorderedMap = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << unorderedMap["kenneth"] << ", " << unorderedMap["JeNniFer"] << ", " << unorderedMap["LYNN"] << ", " << unorderedMap["sole"]; // expected output: /* 2019, 2010, 28, 31 */ |
3. Full Examples
Below is a full example demonstrating the concepts on this page.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates case insensitive maps. // ============================================================================ #include <iostream> #include <string> #include <exception> #include <map> #include <unordered_map> #include <utility> #include <cctype> void display(const std::string& message); // Makes map keys case insensitive struct case_insensitive_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) < 0; } }; }; // Makes unordered map keys case insensitive struct case_insensitive_unordered_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) == 0; } }; struct hash { std::size_t operator() (std::string str) const { for (std::size_t index = 0; index < str.size(); ++index) { auto ch = static_cast<unsigned char>(str[index]); str[index] = static_cast<unsigned char>(std::tolower(ch)); } return std::hash<std::string>{}(str); } }; }; int main() { try { // Declare map std::map<std::string, unsigned, case_insensitive_map::comp> map = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << map["kenneth"] << ", " << map["JeNniFer"] << ", " << map["LYNN"] << ", " << map["sole"]; display(""); // Declare unordered map std::unordered_map<std::string, unsigned , case_insensitive_unordered_map::hash , case_insensitive_unordered_map::comp> unorderedMap = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << unorderedMap["kenneth"] << ", " << unorderedMap["JeNniFer"] << ", " << unorderedMap["LYNN"] << ", " << unorderedMap["sole"]; } 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 Search For & Find A Specific Element In A Vector Using C++

The following is a module with functions which demonstrates how to search for and find a specific element in a vector using C++.
The function demonstrated on this page is a template, so it should work on vectors of any type. It also uses a predicate to determine the item to select.
1. Find
The example below demonstrates the use of ‘Utils::find‘ to find the first element in a sequence of values based on a predicate.
The predicate determines the item to find.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Find // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate = [](const auto& x) { return x.size() >= 8; }; // Get the result auto name = Utils::find(names, predicate); // Display the result std::cout << "Name: " << (*name); // expected output: /* Name: Jennifer */ |
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 39 40 41 42 43 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 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: find * USE: Returns the first element in the given range [first, last) based on a predicate * @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: A Pointer to the first element that satisfies the predicate, nullptr otherwise */ template<typename RandomIt, typename T = typename std::iterator_traits<RandomIt>::value_type, typename Pred> T* find(RandomIt first, RandomIt last, const Pred& predicate) { T* result = nullptr; auto iter = std::find_if(first, last, predicate); if (iter != last) { result = &(*iter); } return result; } /** * FUNCTION: find * USE: Returns the first element in the collection based on a predicate * @param source: The collection to find items * @param predicate: A function to test each element for a condition * @return: A Pointer to the first element that satisfies the predicate, nullptr otherwise */ template<typename T, typename Pred> T* find(std::vector<T>& source, const Pred& predicate) { return find<typename std::vector<T>::iterator, T, Pred>(source.begin(), source.end(), predicate); } }// 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 39 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 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 predicate auto predicate = [](const auto& x) { return x.size() >= 8; }; // Get the result auto name = Utils::find(names, predicate); // Display the result 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 Filter & Select Items In An Array/Vector/Container & Get The Results Using C++

The following is a module with functions which demonstrates how to filter and select items in an array/vector/container, and get the results using C++.
The function demonstrated on this page is a template, so it should work on containers of any type. It also uses a predicate to determine the items to select.
1. Filter – Integer Array
The example below demonstrates the use of ‘Utils::filter‘ to filter an integer array based on a predicate and return its results.
The predicate determines the items to filter and select.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Filter - Integer Array // Declare numbers int numbers[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(numbers) / sizeof(numbers[0]); // Declare predicate auto predicate = [](const auto& x) { return x == 1987 || x == 1991; }; // Get results auto results = Utils::filter(numbers, numbers + size, predicate); // Display the results for (const auto& number : results) { std::cout << "Number: " << number << std::endl; } // expected output: /* Number: 1987 Number: 1991 */ |
2. Filter – String Vector
The example below demonstrates the use of ‘Utils::filter‘ to filter a sequence of values based on a predicate and return its results.
The predicate determines the items to filter and select.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Filter - String Vector // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate = [](const auto& x) { return x == "Kenneth" || x == "Jennifer"; }; // Get the results auto results = Utils::filter(names.begin(), names.end(), predicate); // Display the results for (const auto& name : results) { std::cout << "Name: " << name << std::endl; } // expected output: /* Name: Kenneth Name: Jennifer */ |
3. 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 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: filter * USE: Filters a sequence of values in the given range [first, last) * based on a predicate and returns its results * @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: A collection that contains elements from the input * sequence that satisfies the condition */ template<typename InputIt, typename T = typename std::iterator_traits<InputIt>::value_type, typename Pred> std::vector<T> filter(InputIt first, InputIt last, const Pred& predicate) { std::vector<T> result; std::copy_if(first, last, std::back_inserter(result), predicate); return result; } }// http://programmingnotes.org/ |
4. 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 50 51 52 53 54 55 56 57 58 59 60 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 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 numbers int numbers[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(numbers) / sizeof(numbers[0]); // Declare predicate auto predicate = [](const auto& x) { return x == 1987 || x == 1991; }; // Get results auto results = Utils::filter(numbers, numbers + size, predicate); // Display the results for (const auto& number : results) { display("Number: " + std::to_string(number)); } display(""); // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate2 = [](const auto& x) { return x == "Kenneth" || x == "Jennifer"; }; // Get the results auto results2 = Utils::filter(names.begin(), names.end(), predicate2); // Display the results for (const auto& name : results2) { 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.