To make std::ranges::find_if()
case-insensitive when searching through a container of strings, you need to provide a predicate that performs a case-insensitive comparison.
First, define a case-insensitive comparison function. You can use the std::tolower()
function to convert characters to lowercase:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
bool caseInsensitiveCompare(char a, char b) {
return std::tolower(a) == std::tolower(b);
}
std::ranges::find_if()
with the PredicateNext, use this function within a predicate for std::ranges::find_if()
:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
bool caseInsensitiveCompare(char a, char b) {
return std::tolower(a) == std::tolower(b);
}
bool caseInsensitiveStringCompare(
const std::string& str,
const std::string& target
) {
return std::equal(
str.begin(),
str.end(),
target.begin(),
target.end(),
caseInsensitiveCompare
);
}
int main() {
std::vector<std::string> words{
"Apple", "banana", "Cherry" };
std::string target = "BANANA";
auto result = std::ranges::find_if(words,
[&](const std::string& word) {
return caseInsensitiveStringCompare(
word, target
);
});
if (result != words.end()) {
std::cout << "Found: " << *result << "\n";
} else {
std::cout << "Not found\n";
}
}
Found: banana
In this example:
caseInsensitiveCompare()
converts each character to lowercase before comparing.caseInsensitiveStringCompare()
uses std::equal()
to compare two strings case-insensitively.std::ranges::find_if()
calls caseInsensitiveStringCompare()
within a lambda function to perform the case-insensitive search.This method works well for ASCII characters. For more complex scenarios involving Unicode characters, consider using libraries like ICU (International Components for Unicode) to handle case conversion and comparison.
By using a custom comparison function, you can effectively perform case-insensitive searches in a container of strings with std::ranges::find_if()
.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 8 main searching algorithms in the C++ standard library, including find()
, find_if()
, find_if_not()
, find_first_of()
, adjacent_find()
, search_n()
, search()
, and find_end()
.