Search⌘ K
AI Features

Find Items in a Container

Explore how to use the C++ STL's find and find_if algorithms to locate elements within containers such as vectors. Understand their usage with basic types and custom structs, and learn to filter multiple matches using ranges views to enhance container data management.

We'll cover the following...

The algorithm library contains a set of functions for finding elements in a container. The std::find() function, and its derivatives, search sequentially through a container and return an iterator pointing to the first matching element, or the end() element if there's no match.

How to do it

The find() algorithm works with any container that satisfies the Forward or Input iterator iteratorqualifications. For this recipe, we'll use vector containers. The find() algorithm searches sequentially for the first matching element in a container. In this recipe, we'll walk through a few examples:

  • We'll start by declaring a vector of int in the main() function:

int main() {
const vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
...
}
  • Now, let's search for the element with the value ...