// John W. Clark // stl vector and iterator sample #include #include using namespace std; /* * vectors are automagicly resizing arrays * they support random access in constant time * inserts take linear time */ int main() { vector v; // no memory given here v.push_back(42); // allocates memory and places at back for ( int i = 0 ; i < 10 ; ++i ) v.push_back(i); v.push_back(86); cout << "size = " << v.size() << endl; cout << "front = " << v.front() << endl; cout << "back = " << v.back() << endl; v.pop_back(); // removes element at back end // if you want to remove from both use a deque or list v.resize( 15, -999 ); // resize and set values // the value only gets applied to new elements v.push_back( -72 ); for ( size_t i = 0 ; i < v.size() ; ++i ) cout << v[i] << " "; cout << endl; // use iterators to traverse for ( vector::iterator i = v.begin() ; i != v.end() ; ++i ) cout << *i << " "; cout << endl; // iterators get used just like pointers // if the container support random access // you may do pointer arithmetic vector::iterator vii; vii = v.begin() + 4; // erase call on single element and range v.erase( vii ); v.erase( vii + 3, vii + 9 ); for ( vector::iterator i = v.begin() ; i != v.end() ; ++i ) cout << *i << " "; cout << endl; // using the sort function from the algorithms library sort( v.begin(), v.end() ); for ( vector::iterator i = v.begin() ; i != v.end() ; ++i ) cout << *i << " "; cout << endl; return 0; }