// program with some examples of calling the assert macro. When we // uncomment the line that defines NDEBUG, the assertions are turned // off (not even compiled). #include #include #include #include // #define NDEBUG #include using namespace std; int binary_search(const vector & v, int value) { // the following assertion worked, but was expensive (slow) // assert(is_sorted(v.begin(), v.end())); int low = 0; int high = v.size() - 1; while (low <= high) { // simpler assertion that works fairly well without increasing // the complexity assert(v[low] <= v[high]); int mid = low + (high - low) / 2; if (v[mid] == value) { return mid; } else if (v[mid] < value) { low = mid + 1; } else { // v[mid] > value high = mid - 1; } } return -1; } // program that transfers text from s1 to s2 void transfer(string & s1, string & s2) { s2 = s2 + ", " + s1; s1 = ""; // it seemed that this assertion would always be true because of // the comma added to s2, but that's not true when the function is // passed the same string twice assert(!s2.empty()); } // program that tests binary_search by constructing a vector of given // size, filling it up with 0 through size-1, then randomizing and // calling binary_search again. void test(int size) { vector v; v.reserve(size); for (int i = 0; i < size; i++) { v.push_back(i); } cout << "working with vector of size " << size << endl; cout << "results when sorted:" << endl; int okay = 0; for (int i = 0; i < size; i++) { if (binary_search(v, i) == i) { okay++; } } cout << okay << " values correct" << endl; random_shuffle(v.begin(), v.end()); cout << "results when shufled:" << endl; okay = 0; for (int i = 0; i < size; i++) { if (binary_search(v, i) == i) { okay++; } } cout << okay << " values correct" << endl; cout << endl; } int main() { srand (time(nullptr)); // to seed the random number generator // test(10000); string s1 = "hello"; string s2 = "there"; cout << "s1 = '" << s1 << "', s2 = '" << s2 << "'" << endl; transfer(s1, s1); cout << "s1 = '" << s1 << "', s2 = '" << s2 << "'" << endl; return 0; }