The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate a two-dimensional vector length
C++: hypot avoids unnecessary intermediate overflow in the sum of squares.
C++✓ Tested
Check an upper integer bound before adding
C++: For these nonnegative values, compare against the maximum minus the addend first.
C++✓ Tested
Find the greatest common divisor with the standard library
C++: std::gcd computes a nonnegative integer common divisor.
C++✓ Tested
Find the least common multiple with the standard library
C++: std::lcm combines positive integer periods into a common cycle.
C++✓ Tested
Format an integer into a caller-owned buffer
C++: to_chars avoids allocation and reports whether the buffer was large enough.
C++✓ Tested
Handle a failed string-to-integer conversion
C++: stoi throws invalid_argument when no conversion can be performed.
C++✓ Tested
Parse a complete integer without exceptions
C++: from_chars reports both an error code and the first unconsumed character.
C++✓ Tested
Parse a hexadecimal integer with from_chars
C++: An explicit radix controls digit interpretation without a locale dependency.
C++✓ Tested
Reject infinite and NaN numeric values
C++: std::isfinite excludes special floating-point values.
C++✓ Tested
Round halfway floating-point values away from zero
C++: std::round has an explicit halfway rule different from truncation.
C++✓ Tested