Locating Values in C++ Using the Find Algorithm

By John Paul Mueller, Jeff Cogswell

The Standard Library in C++ contains a number of functions to find something you need within a container. Locating what you need as efficiently as possible is always a good idea. Unlike your closet, you want your applications well organized and easy to manage! The four common find() algorithms are

  • find()

  • find_end()

  • find_first_of()

  • find_if()

The algorithm you use depends on what you want to find and where you expect to find it. You’ll likely use the plain find() algorithm most often. The FindString example shows how to locate a particular string within vector — you can use the same approach to locate something in any container type:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
    vector<string> Words;
    vector<string>::iterator Result =
        find(Words.begin(), Words.end(), "LightGray");
    if (Result != Words.end())
        cout << *Result << endl;
        cout << "Value not found!" << endl;
    Result = find(Words.begin(), Words.end(), "Black");
    if (Result != Words.end())
        cout << *Result << endl;
        cout << "Value not found!" << endl;

The example starts with vector containing Color strings. In both cases, the code attempts to locate a particular color within vector. The first time the code is successful because LightGray is one of the colors listed in vector. However, the second attempt is thwarted because Black isn’t one of the colors in vector. Here’s the output from this example:

Value not found!

Never assume that the code will find a particular value. Always assume that someone is going to provide a value that doesn’t exist and then make sure you provide a means of handling the nonexistent value. In this example, you simply see a message stating the value wasn’t found. However, in real-world code, you often must react to situations where the value isn’t found by

  • Indicating an error condition

  • Adding the value to the container

  • Substituting a standard value

  • Defining an alternative action based on invalid input

The find() algorithm is very flexible. You can use it for external and internal requirements. Even though the example shows how you can locate information in an internal vector, you can also use find() for external containers, such as disk drives. Have some fun with this one — experiment with all the containers you come across.