C++ <algorithm> std::find
The std::find
function template in C++ is part of the <algorithm> header and is used to search for the first occurrence of a specified value within a range defined by two iterators. If the value is found, it returns an iterator pointing to the first occurrence; otherwise, it returns the end iterator.
Syntax of std::find
template <class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& val);
Parameters of std::find
Parameter | Description |
---|---|
first | An input iterator to the initial position in a sequence. |
last | An input iterator to the final position in a sequence (one past the last element). |
val | The value to search for in the range. |
Return Value of std::find
An iterator to the first element in the range that compares equal to val
. If no such element is found, the function returns last
.
Exceptions for std::find
Throws if any of the element comparisons or operations on the iterators throw exceptions. Note that invalid parameters cause undefined behavior.
Examples for algorithm find function
Example 1: Using std::find with an Array
In this example, we use std::find
to search for a value in an array.
Program
#include <iostream>
#include <algorithm> // For std::find
int main() {
int myints[] = {10, 20, 30, 40};
int* p;
p = std::find(myints, myints + 4, 30);
if (p != myints + 4)
std::cout << "Element found in myints: " << *p << '\n';
else
std::cout << "Element not found in myints\n";
return 0;
}
Output
Element found in myints: 30
Explanation
- We include the necessary headers:
<iostream>
for input/output operations and<algorithm>
for thestd::find
function. - An array
myints
is initialized with the values {10, 20, 30, 40}. - We use
std::find
to search for the value 30 in the array. The function searches in the range [myints
,myints + 4
). - If the value is found,
p
points to the element, and we print its value. Otherwise, we print that the element was not found.
Example 2: Using std::find with a Vector
This example demonstrates how to use std::find
to search for a value in a std::vector
.
Program
#include <iostream>
#include <vector>
#include <algorithm> // For std::find
int main() {
std::vector<int> myvector = {10, 20, 30, 40};
auto it = std::find(myvector.begin(), myvector.end(), 30);
if (it != myvector.end())
std::cout << "Element found in myvector: " << *it << '\n';
else
std::cout << "Element not found in myvector\n";
return 0;
}
Output
Element found in myvector: 30
Explanation
- We include the necessary headers:
<iostream>
for input/output operations,<vector>
for thestd::vector
container, and<algorithm>
for thestd::find
function. - A vector
myvector
is initialized with the values {10, 20, 30, 40}. - We use
std::find
to search for the value 30 in the vector. The function searches in the range [myvector.begin()
,myvector.end()
). - If the value is found,
it
points to the element, and we print its value. Otherwise, we print that the element was not found.
Example 3: Using std::find with a List
In this example, we use std::find
to search for a value in a std::list
.
Program
#include <iostream>
#include <list>
#include <algorithm> // For std::find
int main() {
std::list<int> mylist = {10, 20, 30, 40};
auto it = std::find(mylist.begin(), mylist.end(), 25);
if (it != mylist.end())
std::cout << "Element found in mylist: " << *it << '\n';
else
std::cout << "Element not found in mylist\n";
return 0;
}
Output
Element not found in mylist
Explanation
- We include the necessary headers:
<iostream>
for input/output operations,<list>
for thestd::list
container, and<algorithm>
for thestd::find
function. - A list
mylist
is initialized with the values {10, 20, 30, 40}. - We use
std::find
to search for the value 25 in the list. The function searches in the range [mylist.begin()
,mylist.end()
). - Since the value 25 is not present in the list,
it
is equal tomylist.end()
. - The program prints “Element not found in mylist” because the value was not found.
Examples for Exceptions Thrown by find function
The std::find
function can throw exceptions in two primary scenarios:
- If the comparison between the elements throws an exception.
- If an operation on the iterators (such as dereferencing or incrementing) throws an exception.
Example 1: Exception Thrown by Element Comparison
This example demonstrates a case where the comparison operation throws an exception during execution.
Program
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
class FaultyComparator {
public:
bool operator()(int a, int b) const {
if (a == -1 || b == -1) {
throw std::runtime_error("Invalid value encountered during comparison.");
}
return a == b;
}
};
int main() {
std::vector numbers = {-1, 10, 20, 30};
try {
auto it = std::find_if(numbers.begin(), numbers.end(), [](int n) {
if (n == -1) {
throw std::runtime_error("Faulty value found during comparison.");
}
return n == 20;
});
if (it != numbers.end()) {
std::cout << "Element found: " << *it << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
} catch (const std::runtime_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output
Exception caught: Faulty value found during comparison.
Explanation
- The program defines a lambda function inside
std::find_if
that throws an exception if the value-1
is encountered during the comparison. - A vector
numbers
is initialized, containing a faulty value-1
. - The
std::find_if
function applies the lambda to each element. When it encounters the faulty value, the lambda throws an exception. - The exception is caught in the try-catch block, and an error message is printed.
Example 2: Exception Thrown by an Iterator
This example demonstrates a case where a custom iterator throws an exception during iteration.
Program
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
class FaultyIterator {
public:
using iterator_category = std::input_iterator_tag;
using value_type = int;
using difference_type = std::ptrdiff_t;
using pointer = const int*;
using reference = const int&;
FaultyIterator(const int* ptr, bool fail_after = false)
: ptr(ptr), fail_after(fail_after), count(0) {}
reference operator*() const {
if (fail_after && count >= 2) {
throw std::runtime_error("Iterator error during dereference.");
}
return *ptr;
}
FaultyIterator& operator++() {
++ptr;
++count;
return *this;
}
bool operator!=(const FaultyIterator& other) const {
return ptr != other.ptr;
}
private:
const int* ptr;
bool fail_after;
int count;
};
int main() {
int arr[] = {1, 2, 3};
try {
auto it = std::find(
FaultyIterator(arr, true),
FaultyIterator(arr + 3),
3
);
if (it != FaultyIterator(arr + 3)) {
std::cout << "Element found: " << *it << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
} catch (const std::runtime_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Output
Exception caught: Iterator error during dereference.
Explanation
- The program defines a custom iterator
FaultyIterator
that throws astd::runtime_error
exception after accessing two elements. - An array
arr
is initialized with three elements. - The
std::find
function searches for the value3
in the range. The custom iterator throws an exception during the third access. - The exception is caught in the
try-catch
block, and an error message is printed.