C++ Standard Library
C++ Library Interfaces: Containers, Ranges, and Results
C++ Library Interfaces let you store, search, reorder, and summarize data through documented operations. A library interface specifies how you request an operation, what inputs it accepts, and what effects and results you can expect. You use that contract without needing the implementation details. The snippets here use C++17, assume the named headers are included, and place executable statements inside a function.
Read the operation's contract
A header supplies declarations for related facilities. Use the vector header for std::vector, algorithm for std::sort, std::find, and std::count, and numeric for std::accumulate. Include the headers you actually need rather than relying on another header to include them indirectly.
The std:: prefix identifies the standard-library namespace. A vector is a container. Its member operations use dot notation, such as readings.size(). Separate algorithms receive their inputs as arguments, such as std::sort(readings.begin(), readings.end()).
Operation | Header | Contract to remember |
|---|---|---|
v.size() | vector | Returns the number of stored elements |
v.at(i) | vector | Accesses index i, checking that it is within the stored elements |
v.push_back(value) | vector | Appends one element |
v.reserve(n) | vector | Requests capacity of at least n without changing size |
v.resize(n, value) | vector | Sets size to n; added elements receive value |
std::sort(first, last) | algorithm | Reorders the selected range into ascending order by default |
std::find(first, last, value) | algorithm | Returns the first matching position, or last if absent |
Size and capacity answer different questions. Size counts elements that exist; capacity describes how many elements the vector can hold without reallocating storage. Reserving space does not create values you can access.
Pass the intended iterator range
An iterator is an object representing a position that supports operations for traversing a sequence. For a vector, begin() identifies the first element when one exists, and end() identifies the position just beyond the last element.
Algorithms commonly use the range notation [first,last): include the first position and exclude the stopping position. Passing begin() and end() therefore selects all stored elements. An empty vector has equal beginning and ending iterators, representing an empty range.
Example: A monitoring program stores four integer readings and sorts them using the complete range.
std::vector readings{12, 18, 12, 6};
std::sort(readings.begin(), readings.end());The resulting sequence is 6, 12, 12, 18. Sorting changes the element order, while preserving the number of elements and their values. Vector indices start at zero, so readings.at(0) accesses the first value.
Interpret results and preserve validity
Different interfaces return different kinds of results. std::count returns the number of matching elements. std::find returns a position. Test that position against the search's stopping iterator before dereferencing it with *pos.
For readings x0 through xn−1, the mathematical targets for a total and mean are
std::accumulate starts with its third argument and adds each selected element. That initial argument also determines the running total's type.
auto total = std::accumulate(
readings.begin(), readings.end(), 0.0);
double mean = total / readings.size();Here, 0.0 makes the running total a double, and division uses floating-point arithmetic. The total is 48 and the mean is 12.0. Starting with integer 0 instead uses an integer running total; fractional contributions can be lost even if you later assign the result to a double.
What to remember
- Include the header declaring each facility.
- Distinguish member operations from separate algorithms.
- Supply a valid range with an excluded stopping position.
- Check search results before reading them, and choose an appropriate accumulation type.
Example: Summarizing Lab Delivery Times
A lab records four delivery times, in minutes: 34, 27, 42, and 27. A fifth delivery takes 30 min. Use C++ Library Interfaces to update and summarize the records. All snippets use C++17, run inside a function, and assume the required vector, algorithm, and numeric headers are included. All operations succeed.
A half-open range includes its starting position and excludes its stopping position. Use the complete vector range for each algorithm.
std::vector times{34, 27, 42, 27};a) Append the fifth delivery, sort all recorded times, and determine the number of measurements and the third-smallest time.
- The initial number of measurements is ________. Append the fifth time with the vector's member operation:
times.push_back(30);- Sort every stored element by passing the beginning and ending iterators:
std::sort(times.begin(), times.end());The sorted sequence is ________ in minutes. The stopping iterator excludes the position beyond the last measurement; it does not exclude the last measurement itself.
- Read the size and the third element:
auto number = times.size();
int third = times.at(2);Indexing starts at zero, so index 2 selects the third element. There are 5 measurements, and the third-smallest time is 30 min.
b) Calculate the total delivery time and the mean delivery time. Report the mean to one decimal place.
- Accumulate the full sorted range. Start with 0.0 so the running total has type double:
auto total = std::accumulate(
times.begin(), times.end(), 0.0);The first two sorted times sum to ________. Including the third gives ________. Adding the remaining times gives
- Divide by the number of recorded deliveries, rather than by the last valid index:
double mean = total / times.size();The numerator is a double, so the division uses floating-point arithmetic. The total delivery time is 160 min, and the mean is 32.0 min. The mean lies between the smallest and largest recorded times, providing a useful check.
c) Determine whether a 27 min delivery is present, and show the check required before reading the returned iterator's value.
- Search the complete vector using the separate algorithm:
auto pos = std::find(times.begin(), times.end(), 27);
bool found = pos != times.end();The first sorted element is 27, so the algorithm returns the beginning iterator. It does not return the number 27 or the number of matches.
- Check the returned position before reading its element. The comparison is true here, so the program may safely access the matched time inside this branch:
if (pos != times.end()) {
int matchedTime = *pos;
}Using *pos is called dereferencing. If a search returns times.end(), that position represents no element and must not be read this way.
The search reports a match, and the matched delivery time is 27 min.
A team is choosing containers for a lab-inventory program and wants each choice to match the guarantee it needs. Match each standard library container to the description of how it stores elements and what it promises about order, uniqueness or insertion cost.
Sorted collection of unique keys that stores no separate mapped values
Associative container of unique keys kept in sorted order, each key paired with a mapped value
Hash-based container of unique keys with mapped values and average constant-time lookup, in no guaranteed order
Double-ended sequence with constant-time insertion and removal at both the front and the back
Contiguous sequence that grows on demand, with amortized constant-time insertion at the back
Contiguous sequence whose fixed length is part of its type and cannot change at run time
std::set
std::unordered_map
std::deque
std::vector
std::map
std::array
A C++17 service desk program stores waiting times in minutes. With the required headers included, it executes these statements in order. Assume every operation succeeds.
std::vector waits{7, 11, 16};
waits.reserve(12);
waits.resize(5, 4);
waits.push_back(9);Complete the table at each checkpoint. Enter exact integers for the number of stored elements and the value returned by waits.at(waits.size() - 1). Report size, not capacity.
| Checkpoint | Stored elements | Last waiting time (min) |
| After reserve(12) | ||
| After resize(5, 4) | ||
| After push_back(9) |