C++

How Do You Find Something in a Vector in C++?

C++ vector does not have a find member function. However, the algorithm library has a find() function of different types that can be used to find something in a C++ vector. The algorithm library has four groups of find() functions that can be classified as Find, Find End, Find First, and Adjacent Find.

In order to use the vector and algorithm libraries, the C++ program should begin with:

#include <algorithm>

#include <vector>

#include <iostream>

using namespace std;

This tutorial gives the basics of finding a value in a C++ vector. All code in this tutorial are in the main() function, unless otherwise indicated. If the vector consists of strings, then use the string class; and do not use “const char* ”. In this case, the string class has to be included as well, like so:

#include <string>

Article Content

Find

InputIterator find(InputIterator first, InputIterator last, const T& value);

The following code uses this function to know if the flower, “Cornflower” is among a vector list of flowers:

#include <algorithm>

#include <vector>

#include <string>

#include <iostream>

using namespace std;

 

    int main()
    {
        vectorvtr = {"Dog Rose", "Honeysuckle", "Enchanter's nightshade", "Columbine", "Kingcup", "Cornflower", "Water avens", "Forget-me-not"};

        vector::iterator it = find(vtr.begin(), vtr.end(), "Cornflower");

        if (it == vtr.end())
cout<< "Flower was not found!" <<endl;
        else
cout<< "Flower found at index: " << it - vtr.begin() <<endl;

        return 0;
    }

The output is:

Flower found at index: 5

The whole list of the vector has been the target for the finding. From the syntax of the find() function, “first” is vtr.begin() in the code, and “last” is vtr.end() in the code. The value to be looked for from the find() function syntax denoted by const-T&-value, is "Cornflower" in the code.

The find() function scans the vector list from the beginning. If it does not see the value it is looking for, it will reach the end of the vector. The end of the vector is officially vtr.end(), which is just beyond the last element. If it does not see the value it is looking for, it will return the iterator pointing to vtr.end().

The value it is looking for may be in different places in the same vector. When it sees the first of the values it is looking for, it stops there and returns the iterator that is pointing to that value.

Each value in a vector has an index. The first value has index 0, corresponding to vtr.begin(). The second value has index 1, corresponding to vtr.begin() + 1. The third value has index 2, corresponding to vtr.begin() + 2. The fourth value has index 3, corresponding to vtr.begin() + 3; and so on. So, the index of the first value found is given by:

it - vtr.begin()

Case Sensitivity

Finding in a vector is case sensitive. If the value to be found was “CORNFLOWER” for the above program, it would not have been found, and vtr.end() would have been returned.

Range Within Limits

The range must not necessarily be the whole vector. For the above program, the range could have been from index 1 to index 4. That is, from “vtr.begin() + 1” to “vtr.end() – 4”. “vtr.end() – 4” is obtained by subtracting from the back, bearing in mind that vtr.end() is just beyond the very last element.

When the whole vector list is the range, testing whether the return iterator is vtr.end() indicates whether the value was found or not. If the return iterator is vtr.end(), it means the value was not found. Now, when the range is smaller, if the return iterator is the last element of the range chosen, it means the value was either not found or it is the last value of the range.

Note: Searching stops at the last element of the chosen (smaller) range, if the value was not found in that range, or if the value found, is that last element of the chosen range. If the value found was that last element, an iterator pointing to it would be returned. If the value was found before, searching would stop at that element before the last element of the chosen range. The iterator of that element before would be returned.

The following code illustrates this scheme:

    #include <algorithm>

    #include <vector>

    #include <string>

    #include <iostream>

    using namespace std;

 

    int main()
    {
        vectorvtr = {"Dog Rose", "Honeysuckle", "Enchanter's nightshade", "Columbine", "Kingcup", "Cornflower", "Water avens", "Forget-me-not"};

        vector::iterator it = find(vtr.begin() + 1, vtr.end() - 4, "Cornflower");

        if (it == vtr.end())
cout<< "Flower was not found!" <<endl;
        else if (it - vtr.begin() == 4) {    //last element in chosen range
            if (*it == string("Cornflower"))
cout<< "Flower found at index: " << it - vtr.begin() <<endl;
            else
cout<< "Flower was not found in range!" <<endl;
        }    
        else {
cout<< "Flower found at index: " << it - vtr.begin() <<endl;
        }

        return 0;
    }

The output is:

Flower was not found in range!

Now, "Cornflower" is at index 5, and "Kingcup" is at index 4. The last element in the small range chosen for search is "Kingcup". So, the corresponding test condition is “it – vtr.begin() == 4”. Note that the expressions, “vtr.end() – 4” and “it – vtr.begin() == 4” each having 4, is just coincidence.

In order to have "Cornflower" in the search small range, the corresponding test condition will have to be “it – vtr.begin() == 5”. The following code illustrates this:

    #include <algorithm>

    #include <vector>

    #include <string>

    #include <iostream>

    using namespace std;

 

    int main()
    {
        vectorvtr = {"Dog Rose", "Honeysuckle", "Enchanter's nightshade", "Columbine", "Kingcup", "Cornflower", "Water avens", "Forget-me-not"};

        vector::iterator it = find(vtr.begin() + 1, vtr.end() - 3, "Cornflower");

        if (it == vtr.end())
cout<< "Flower was not found!" <<endl;
        else if (it - vtr.begin() == 5) {
            if (*it == string("Cornflower"))
cout<< "Flower found at index: " << it - vtr.begin() <<endl;
            else
cout<< "Flower was not found in range!" <<endl;
        }    
        else {
cout<< "Flower found at index: " << it - vtr.begin() <<endl;
        }

        return 0;
    }

The output is:

Flower found at index: 5

More Than One Occurrence

In the following program, “Cornflower” occurs in more than one place. To find all the indexes of the occurrences, use a while loop to continue search, after the previous occurrence, until the end (vtr.end()) of the vector. The program is:

#include <algorithm>

    #include <vector>

    #include <string>

    #include <iostream>

    using namespace std;

 

    int main()
    {
        vectorvtr = {"Dog Rose", "Cornflower", "Enchanter's nightshade", "Columbine", "Kingcup", "Cornflower", "Water avens", "Cornflower"};

        vector::iterator it = find(vtr.begin(), vtr.end(), "Cornflower");
        while (it != vtr.end()) {
            if (*it == string("Cornflower"))
cout<< "Flower found at index: " << it - vtr.begin() <<endl;
            it++;
        }

        return 0;
    }

The output is:

Flower found at index: 1

Flower found at index: 5

Flower found at index: 7

Finding Integer

A vector may consist of integers. A first integer value can be found using the find() function (from the algorithm library). The following program illustrates this:

#include <algorithm>

#include <vector>

#include <iostream>

using namespace std;

 

    int main()
    {
        vectorvtr = {1, 2, 3, 1, 2, 3, 1, 2, 3};

        vector::iterator it = find(vtr.begin(), vtr.end(), 3);

        if (it == vtr.end())
cout<< "Number was not found!" <<endl;
        else
cout<< "Number found at index: " << it - vtr.begin() <<endl;

        return 0;
    }

The output is:

Number found at index: 2

for the first occurrence of the value, 3.

Predicate

InputIterator find_if(InputIterator first, InputIterator last, Predicate pred);

The function here is find_if() and not just find(). Pred is the name of the function that gives the search criteria. This third argument takes only the function name, without arguments and without parentheses. If the predicate function takes argument, then in the function definition, the parameters for the arguments are given. The following program illustrates this, looking for the first even number in the vector list:

#include <algorithm>

    #include <vector>

    #include <iostream>

    using namespace std;

    bool fn(int n) {
        if ((n % 2) == 0)
            return true;
        else
            return false;
    }

    int main()
    {
        vectorvtr = {1, 3, 5, 7, 8, 9, 10, 11, 12};

        vector::iterator it = find_if(vtr.begin(), vtr.end(), fn);

        if (it == vtr.end())
cout<< "Number was not found!" <<endl;
        else
cout<< "Number found at index: " << it - vtr.begin() <<endl;

        return 0;
    }

The output is:

Number found at index: 4

Note that the whole vector has been searched, with the range, “vtr.begin(), vtr.end()”.

The predicate function name here is, fn. It takes one argument, n an int. As the find_if() function begins scanning the vector from the first element, it calls the predicate function with each number in the vector as argument. Scanning stops when it reaches the first element in the vector where the predicate returns true.

Conclusion

The find() function in the algorithm library exists in four categories, which are: Find, Find End, Find First, and Adjacent Find. Only the category, Find has been explained above, and to a large extent. The explanation given above is the bases for all the find() functions in the algorithm library. Find() functions deal with iterators directly and deal with indexes indirectly. The programmer has to know how to convert iterator to index and general iterator arithmetic as illustrated above.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.