Library contents

C++ std::find

Test whether at least one item has the target price.

A simple example

std::find

  1. Start with 1, 2, 3
  2. Do this Look for 2
  3. Result Found
The requested value matches the second element.

Syntax

C++ syntax
std::find(prices.begin(), prices.end(), 3) != prices.end()
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Check for a price in a sale list

A retailer checks a list of prices for a particular offer. Decide whether the question requires the presence of the price, its position or the number of occurrences before interpreting the result.

Resultyes
lesson.cpp
#include <algorithm>
#include <numeric>
#include <iostream>
#include <vector>

int main() {
    const std::vector<int> prices {8, 3, 12, 3};
    std::cout << ((std::find(prices.begin(), prices.end(), 3) != prices.end()) ? "yes" : "no") << "\n";
    return 0;
}
Output
yes

Two prices are three, so a membership check succeeds. Only one match is required.

Advertisements

Check a badge at equipment pickup

The media desk releases cameras to students whose badge number is on the pickup list. Badge 204 is on the sheet between 101 and 305. The volunteer must match a whole number before handing out a camera.

GivenBadge 204 · pickup list 101, 204, 305
ResultRelease camera
lesson.cpp
#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> badges{101, 204, 305};
    auto found = std::find(badges.begin(), badges.end(), 204);
    std::cout << (found != badges.end() ? "Release camera" : "Check roster");
    return 0;
}
Output
Release camera

The list contains badge 204, so the volunteer can release the camera. The recorded numbers identify students individually.

Check an equipment loan

The school loans projectors to registered classrooms. A volunteer checks for a whole identifier before releasing equipment. Does the requested identifier occur in the list?

GivenRoom 16 in [12, 16, 21]
Worked resultListed

What to watch for

Membership answers a yes-or-no question. Use a count when you need the number of matches.

Documentation for std::find