#include <string>
#include <algorithm>
#include <iostream>
void printArray(int* begin, int* end) {
std::cout << "{";
bool alreadyPrinted = false;
for (int* p = begin; p != end; ++p) {
if (alreadyPrinted) {
std::cout << ", ";
}
std::cout << *p;
alreadyPrinted = true;
}
std::cout << "}";
}
int main() {
// Tiny array
constexpr size_t NUM_FAVORITES = 3;
int favorites[NUM_FAVORITES] = {3, 7, 42};
std::cout << "Favorites: ";
printArray(favorites, favorites+NUM_FAVORITES);
// ^------------------------------------------------- trace through to this point!
std::cout << "\n\n";
// 15 arbitrary values from 0..9
constexpr size_t NUM_VALUES = 15;
int values[NUM_VALUES] = {1, 5, 2, 9, 8, 0, 7, 1, 3, 1, 3, 7, 2, 3, 0};
std::cout << "Initial array: ";
printArray(values, values+NUM_VALUES);
std::cout << "\n\n";
// Use std::count to count how many of each number are in the array
std::cout << "Histogram:\n";
for (int v = 0; v < 10; ++v) {
size_t count = std::count(values, values+NUM_VALUES, v);
std::string stars(count, '*');
std::cout << v << ": " << stars << std::endl;
}
// Use std::reverse to flip the array
std::reverse(values, values+NUM_VALUES);
std::cout << "\nReversed: ";
printArray(values, values+NUM_VALUES);
std::cout << "\n\n";
// Use std::sort to sort the array
std::sort(values, values+NUM_VALUES);
std::cout << "Sorted: ";
printArray(values, values+NUM_VALUES);
std::cout << "\n\n";
// Use std::binary_search to look something up
if (std::binary_search(values, values+NUM_VALUES, 6)) {
std::cout << "Sorted array contains a six!\n\n";
} else {
std::cout << "Sorted array does not contain a six!\n\n";
}
// Use std::lower_bound (a variant of binary search that returns a pointer
// rather than a boolean).
int* near6 = std::lower_bound(values, values+NUM_VALUES, 6);
std::cout << "Nearest item >= 6 is " << *near6
<< ", at values[" << (near6-values) << "]\n\n";
// Use std::unique to collect only the unique elements
int* new_endpoint = std::unique(values, values+NUM_VALUES);
std::cout << "Unique elements: ";
printArray(values, new_endpoint);
std::cout << ", with left-over ";
printArray(new_endpoint, values+NUM_VALUES);
std::cout << "\n\n";
return 0;
}