Start learning free

LESSON 111 OF 667 · ARRAYS I

Checking a C++ Vector for a Value with find

Lesson Read the full explanation

TL ; DR:

A vector has no contains method. Use find(v.begin(), v.end(), x) instead. It returns v.end() when x isn't there.


vector<string> colors = {"red", "green", "blue"};

if (find(colors.begin(), colors.end(), "red") != colors.end()) {
    cout << "We have red" << endl;
}

if (find(colors.begin(), colors.end(), "pink") == colors.end()) {
    cout << "No pink yet" << endl;
}


Full lesson:

Often you need to know if a vector holds some value. Is this name on the guest list? Is this item in the cart?

The find function from <algorithm> answers that. Give it a start position, an end position and the value.

It compares the items between the two positions with the value. It returns the position of the first match.

If nothing matches, it returns the end position, v.end(). That spot is just past the last item.

So compare the result with v.end(). Not equal means found, and equal means missing. The comparison is a bool, so it fits right into an if:

vector<string> cart = {"milk", "bread"};

if (find(cart.begin(), cart.end(), "milk") != cart.end()) {
    cout << "Milk is in the cart" << endl;
}

Text must match exactly. Looking for "Red" finds nothing, because the vector has "red".


Your task

bag holds what is packed for a hike.

If "water" is in bag, print Water is packed. If "tent" is not in bag, print Pack a tent.

Expected output:

Water is packed
Pack a tent
STEP 1 OF 2
    Ctrl + Enter to check

    C++ · ARRAYS I

    Array Membership in C++, explained

    No contains method

    A vector has no contains method. To ask "is this value in the vector?", use find from <algorithm>. It takes a start position, an end position and the value to look for.

    find compares the items between the two positions with the value, and returns the position of the first match. If nothing matches, it returns the end position you gave it, which for a whole vector is v.end(). That position is just past the last item, so it never points at a real item.

    Turning the result into a yes or no

    Compare the result with v.end(). If it is not equal, the value was found. If it is equal, the value is missing. The comparison is a bool, so it fits directly in an if.

    vector<string> colors = {"red", "green", "blue"};
    
    if (find(colors.begin(), colors.end(), "red") != colors.end()) {
        cout << "We have red" << endl;
    }
    
    if (find(colors.begin(), colors.end(), "pink") == colors.end()) {
        cout << "No pink yet" << endl;
    }
    

    This prints We have red and then No pink yet.

    Good to know

    • Exact match. Text must match exactly, case included. In a vector holding "red", looking for "Red" finds nothing.
    • First match only. If the value appears twice, find returns the first one. Subtracting v.begin() from the result gives its index: in {4, 7, 7, 9}, finding 7 gives index 1.
    • Don't use the result as a number or a bool. The result is a position. Only comparing it with end() tells you whether the search worked.
    • Cost. find checks the items one by one, so a long vector means a longer search.

    The exercise: packing a hike

    bag holds "map", "water" and "snacks". The task has two checks:

    1. If "water" is in the bag, print Water is packed. The condition is that find does not return bag.end().
    2. If "tent" is not in the bag, print Pack a tent. This time the condition is that find does return bag.end().
    vector<string> bag = {"map", "water", "snacks"};
    if (find(bag.begin(), bag.end(), "water") != bag.end()) {
        cout << "Water is packed" << endl;
    }
    if (find(bag.begin(), bag.end(), "tent") == bag.end()) {
        cout << "Pack a tent" << endl;
    }
    

    The output is:

    Water is packed
    Pack a tent
    

    The most common slip is mixing up != and ==. With the wrong one, the first message would be missing and the second would be printed for the wrong reason. Read the condition out loud: "the search result is not the end" means found.

    Searching for a variable

    The value does not have to be a literal. You can search for a variable of the same type as the items, such as a string target = "snacks";. The check find(bag.begin(), bag.end(), target) != bag.end() then gives true for the bag above.

    Put the check in its own if for each question you ask. Two separate questions, like "is water there?" and "is a tent missing?", are two separate if statements, and both can run, as they do in this exercise.

    Because the lesson only needs a yes or no, you never need the index. If you do want to know where the match is, keep the result in a variable first and subtract bag.begin() only after you have checked it is not bag.end().

    Key takeaways

    • Use find(v.begin(), v.end(), x) to search a vector.
    • != v.end() means found; == v.end() means missing.
    • Matching is exact, and only the first match is returned.
    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free