Rule A25-4-1 (required, implementation, non-automated)

Ordering predicates used with associative containers and STL sorting and related algorithms shall adhere to a strict weak ordering relation.

Rationale

Ordering predicates that can be passed to associative containers or sorting STL algorithms and related operations must fulfill requirements for a strict weak ordering, e.g.: irreflexivity: FOR ALL x: x < x == false assymetry: FOR ALL x, y: if x < y then !(y < x) transitivity: FOR ALL x, y, z: if x < y && y < z then x < z

Ordering predicates not adhering to these requirements will result in these algorithms not working correctly, which may include infinite loops and other erratic behavior.

Example

//% $Id: A25-4-1.cpp 309738 2018-03-01 15:08:00Z michal.szczepankiewicz $ #include <functional> #include <iostream> #include <set> int main(void) { //non-compliant, given predicate does not return false //for equal values std::set<int, std::greater_equal<int>> s{2, 5, 8}; auto r = s.equal_range(5); //returns 0 std::cout << std::distance(r.first, r.second) << std::endl; //compliant, using default std::less<int> std::set<int> s2{2, 5, 8}; auto r2 = s2.equal_range(5); //returns 1 std::cout << std::distance(r2.first, r2.second) << std::endl; return 0; }

See also

SEI CERT C++ Coding Standard [10]: CTR57-CPP: Provide a valid ordering predicate cppreference.com [16]: C++ concepts: Compare

Rule A26-5-1 (required, implementation, automated) Pseudorandom numbers shall not be generated using std::rand().

Rationale

Using a pseudo-random sequence of numbers requires that it is generated with good statistical properties. Some implementations of std::rand() function have a comparatively short cycle, as a result the numbers can be predictable. Using functionalities from is recommended instead of using std::rand(). Note: std::random_shuffle should not be used, as it is deprecated since C++14 (see A1-11) and one of the available overloads is often implemented in terms of std::rand.

Example

// $Id: A26-5-1.cpp 311495 2018-03-13 13:02:54Z michal.szczepankiewicz $ #include <cstdlib> #include <cstdint> #include <ctime> #include <iostream> #include <random> int main() { std::srand(std::time(nullptr)); int r1 = std::rand() % 100; //non-compliant std::cout << "Random value using std::rand(): " << r1 << std::endl; std::random_device rd; std::default_random_engine eng{rd()}; std::uniform_int_distribution<int> ud{0, 100}; int r2 = ud(eng); //compliant std::cout << "Random value using std::random_device: " << r2 << std::endl; return 0; }

See also

SEI CERT C++ Coding Standard [10]: MSC50-CPP: Do not use std::rand() for generating pseudorandom numbers.