// demonstrates iterator usage with vectors // Mikhail Nesterenko // 11/12/2009 #include #include #include using std::cin; using std::cout; using std:: endl; using std::vector; int main(){ vector v; // inputing the numbers cout << "Enter numbers, 0 to quit: "; int num; cin >> num; while(num!=0){ vector::iterator ip=v.end(); v.insert(ip,num); cin >> num; } // modifying the first element through iterator vector::iterator mod=v.begin(); *mod = *mod + 5; // by dereferencing iterator mod[0] = 55; // by indexing iterator // removing the minimum element // initally, assume the first element is smallest vector::iterator toRemove=v.begin(); int min = *toRemove; // start with the second element and iterate for(vector::iterator ip=toRemove + 1; ip != v.end(); ++ip) if(min > *ip){ // found smaller element toRemove=ip; min = *ip; } v.erase(toRemove); // removing the element to which toRemove points // inserting a new element after 3d element if (v.size() > 3){ // check if there are three elements in the vector vector::iterator toAdd=v.begin()+ 3; // making toAdd point to 3d element // with iterator arithmetic v.insert(toAdd,100); // inserting 100 } sort(v.begin(),v.end()); // sorting elements // printing the sorted numbers cout << "Your numbers sorted: "; for(vector::iterator ip=v.begin(); ip != v.end(); ++ip){ cout << *ip << " "; } cout << endl; }