// Assignment 1 // C++ STL #include #include #include #include using namespace std; //--------------------------------------------------- // Assignment 1, part 1: Tests whether vectors work. void vector_test() { vector vi; vi.push_back(42); vi.push_back(17); vi.push_back(23); cout << vi[0] << " " << vi[1] << " " << vi[2] << endl; } //--------------------------------------------------- // Assignment 1, part 2: // Finds a value within an array between [*begin,*end). // This will search *begin, *(begin+1), ..., *(end-1) for // value, using == for comparison. It returns a pointer // to the first match found. If no match is found, it // returns 'end'. template T *findit(T *begin, T*end, T const &value) { while (begin != end) { if (value == *begin) break; ++begin; } return begin; } // Helper macro: #define ARR_END(arr) (arr + sizeof(arr)/sizeof(arr[0])) // Test the findit function template: void findit_test() { int ia[] = {42, 17, 23, 5, 13, 87}; int *p = findit(ia,ARR_END(ia),99); assert(p==ARR_END(ia)); p = findit(ia,ARR_END(ia),17); assert( (p!=ARR_END(ia)) && (*p == 17)); cout << "found " << *p << endl; string sa[] = {"hello", "foobar", "biff"}; string *ps = findit(sa,ARR_END(sa),string("zzzz")); assert(ps==ARR_END(sa)); ps = findit(sa,ARR_END(sa),string("foobar")); assert((ps!=ARR_END(sa)) && (*ps == "foobar")); cout << "found " << *ps << endl; } //--------------------------------------------------- // Assignment 1, part 3: template int countit(T *begin, T *end, T elem_to_count) { int count = 0; T *p = begin; while (end != (p = findit(p,end,elem_to_count))) { ++count; ++p; } return count; } void count_test() { int numbers[] = {2,7,1,8,2,8,1,8,2,8}; cout << "There are " << countit(numbers,ARR_END(numbers),8) << " \"8\"'s in the array." << endl; } //--------------------------------------------------------- // Test driver for parts 1-3: int main() { vector_test(); findit_test(); count_test(); return 0; }