[cs23021] Vectors question

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Nov 24 14:04:35 EST 2010


> 
> Last week in class I was wondering why vectors were made to work with
> iterators. Why didn't the developers of the vector write implementation so
> that elements can be deleted and inserted from the middle without using
> iterators? Thanks.

Well, Stroustrup's (the creator of C++) thinking is that iterators are
so important for STL that the operations such erase/insert should be
defined using only them. There is, however, a way to insert/erase at a
certain index:

      vector<int>  myvector(100);  // declare a vector of 100 elements
      myvector.insert(myvector.begin() + 10, 42)  // insert number 42
      				       	     	  // at the element
						  // with index 10
						  
      myvector.erase(myvector.end() - 5) // remove fifth from last element


Thanks,
-- 
Mikhail


More information about the cs23021-2 mailing list