Vectors
Basics A vector is like an array, but more flexible A vector provides (constant time) random access to its elements A vector may be dynamically resized Constant time insertion or removal at the end Linear time ins/rem elsewhere
Example #include using namespace std; … vector v; assert(v.size == 0); v.insert(v.begin(), 3); assert(v.size() == 1);
Default constructor #include using namespace std; … /* create an empty vector v of specified type */ vector v;
Copy constructor #include using namespace std; … /* create an vector v1 which is a copy of v (types must be the same) */ vector v1(v);
Sized constructor #include using namespace std; … /* create an vector v which of specified size, using the default constructor */ vector v1(size);
Initialized constructor #include using namespace std; … /* create an vector v which of specified size, using the supplied value */ vector v1(size, value);
Range constructor #include using namespace std; … /* create an vector v of the specified size, us values all values from begin to end */ vector v(begin, end);
Removing elements v.clear();// deletes all elements v.erase(pos);// deletes element at pos
Inserting elements // insert val at pos v.insert(pos, val); // insert n copies of val at pos v.insert(pos, n, val); // a copy of v.beg.. v.end-1 is inserted // at pos v.insert(pos, beg, end);
Operations for all containers Default constructor /* Initialize the object to an empty state */
Parameterized constructors /* Various specialized ways to specify the initial contents of the container */
Copy constructors /* A container of the same type must be passed by value. */
destructor /* Executes when the container goes out of scope */
c.empty() /* Returns true if c is empty, false otherwise. */
c.size() /* Returns the number of elements in c. */
c.max_size() /* Returns the number of elements that can be inserted into c. */
c.swap(c1) /* Swaps the elements c and c1 */
c.begin() /* Returns an interator to the first element in c. */
c.end() /* Returns an interator succeeding the last element in c. */
c.rbegin() /* (reverse) Returns an interator pointing to the last element in c. */
c.rend() /* (reverse) Returns an interator pointing one past the first element in c */
c.insert(pos, val) /* Inserts val into pos (pos is an iterator) */
c.erase(begin, end) /* Deletes elements from begin to end-1 */
c.clear() /* Deletes all elements */
Operators /* =, ==, !=,, >=x */