Library contents

C++ std::count

Count how many elements equal the price printed on an offer sign.

A simple example

std::count

  1. Start with 2, 3, 2
  2. Do this Count matches for 2
  3. Result 2 matches
Both the first and last elements contribute one to the count.

Syntax

C++ syntax
std::count(prices.begin(), prices.end(), 3)
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

Count items at the offer price

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.

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

int main() {
    const std::vector<int> prices {8, 3, 12, 3};
    std::cout << (std::count(prices.begin(), prices.end(), 3)) << "\n";
    return 0;
}
Output
2

The price of three appears twice, so two items qualify for the offer.

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. The supervisor asks how often the first quantity occurs in the complete batch. Count all matching entries.

Given6 · 2 · 6 · 0
Worked result2

Review print quantities

A print room records four job quantities, including a cancelled job. The supervisor asks how often the first quantity occurs in the complete batch. Count all matching entries.

Given3 · 0 · 8 · 3
Worked result2

What to watch for

Count the matching elements rather than the distinct matching prices.

Documentation for std::count