std find

suggest change
template <class InputIterator, class T>
InputIterator find (InputIterator first, InputIterator last, const T& val);

Effects

Finds the first occurrence of val within the range [first, last)

Parameters

first => iterator pointing to the beginning of the range last => iterator pointing to the end of the range val => The value to find within the range

Return

An iterator that points to the first element within the range that is equal(==) to val, the iterator points to last if val is not found.

Example

The example uses std::ranges::find (C++20) and class template argument deduction (C++17).

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

  //create a vector
  const std::vector intVec{4, 6, 8, 9, 10, 30, 55, 100, 45, 2, 4, 7, 9, 43, 48};

  const auto itr_9 = std::ranges::find(intVec, 9); // occurs twice
  const auto itr_43 = std::ranges::find(intVec, 43); // occurs once
  const auto itr_50 = std::ranges::find(intVec, 50); // does not occur

std::cout << "first occurrence of: " << *itr_9 << '\n';
std::cout << "only occurrence of: " << *itr_43 << '\n';

/*
  let's prove that itr_9 is pointing to the first occurrence
  of 9 by looking at the element after 9, which should be 10 
  not 43
*/
std::cout << "element after first 9: " << *(itr_9 + 1) << '\n';

/*
  to avoid dereferencing intVec.end(), let's look at the 
  element right before the end
*/
std::cout << "last element: " << intVec.back() << '\n';
}
first occurrence of: 9
only occurrence of: 43
element after first 9: 10
last element: 48

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents