// program illustrating use of vectors. bds 2004Mar /* Input is a sequence of numbers. Output is the same sequence of numbers, in the same order, and with each number on a new line. Also the largest number is to be indicated by the word "largest" appearing after the number. Similarly for the smallest. */ #include #include using namespace std; // comments beginning with //// mark first use of each vector functionality int main() { vector A; //// default constructor - empty vector float x; // input the numbers cin >> x; while (cin) { A.push_back(x); //// push_back() - grow size by one, put x in. cin >> x; } if ( A.size() == 0 ) return 0; //// size() - returns an int, current size. // find the position of the max (illustrating index use) float maxval = A[0]; //// operator[] (indexing) //// relation to int as index type int i, maxpos = 0; //// int default constructor //// int copy constructor for( i = 1; i < A.size(); ++i ) if ( A[i] > maxval ) { maxval = A[i]; maxpos = i; } // find the position of the min (illustrating iterator use) float minval = A.front(); //// front() - first element, a float vector::iterator j, minptr = A.begin(); //// ::iterator - a type "owned" by the vector type //// ::iterator's default constructor //// begin() - returns an ::iterator pointing to front //// ::iterator copy constructor for ( j = A.begin() + 1; j < A.end(); ++j ) //// end() - returns an ::iterator poiting beyond end //// ::iterator operator+ - add an int to it. //// ::iterator assignment //// ::iterator operator< - compare positions //// ::iterator operator++ - point to next posn. if ( *j < minval ) { minval = *j; minptr = j; } //// ::iterator operator* - returns the value being //// pointed to, a float //// ::iterator operator= - ::iterator assignment // output the result for ( j = A.begin(); j < A.end(); ++j ) { cout << *j; if ( minptr == j ) cout << " smallest"; if ( maxpos == j - A.begin() ) cout << " largest"; //// ::iterator operator- - difference is an int. cout << endl; } return 0; }