- Safe to pass as a parameter or assign to
- Size increases when necessary means no memory management problem
- Comparisons (==, < etc.) works "as it should"
- No forced boundary limit checks in indexing
- Easy to write code that may be inefficient in parameter passing
- Passing arrays to libraries that use C arrays is difficult
Comparisons between C arrays and vector:
operation | array | vector |
Creation | int t[10] | vector<int> t(10); or vector<int> t; (empty) |
Assignment | in a loop | t1 = t2 |
Indexing | t[i] | t[i] or t.at(i) |
Inserting to the end | not possible | t.push_back(item) |
Combining | not possible | t1.insert(t1.end(), t2.begin(), t2.end()) |
Size | programmer must know | t.size() |
Emptying | not possible | t.clear() |
Comparison | in a loop | t1 == t2 (likewise <> |
Insertion to the middle | not possible | t.insert(iterator, item) |
Searching | in a loop | find(t.begin(), t.end(), item) |
Exchange of values | in a loop | t1.swap(t2) |
vector< type > var;An empty vector
vector< type > var(vector< type >); Initialization with another vector
vector< type > var(int);A vector of the size int with elements of the type
vector< type > var(int, element);A vector with int elements initialized to element
Operations:
vector[int] // Indexing the vector at int.
vector1 = vector2 // Assignment
vector1 == vector2 // Comparison
vector1 != vector2vector1 < vector2vector1 <= vector2vector1 > vector2 vector1 >= vector2
Functions:
swap(vector1, vector2) // swaps the contents
Own functions:
type at( int ) | Indexing the vector at int |
type front() | The first element |
type back() | Last element |
vector<type>::size_type size() | number of elements |
bool empty() | true if vector is empty |
void push_back(element) | Element is added to the end of vector |
void pop_back() | Last element is removed, size gets smaller by one |
void clear() | Empty the vector completely |
iterator being() | An iterator to the beginning |
iterator end() | An iterator to the end |
#include <algorithm>
Functions:
void sort( array, array+size );
void sort( vector.begin(), vector.end() );
// Sorting the vector or array into an ascending order
bool compare(const item&, const item&);
void sort( array, array+size, compare );
void sort( vector.begin(), vector.end(), compare );
// Sort can be given a comparison function as a third parameter
// Function returns true if the first parameter is smaller than the second.
void operations(const item&);
void for_each( array, array+size, operations );
void for_each( vector.begin(), vector.end(), operation );
// Calls the function operation for each element in the array or vector at a time.
Reference: cplusplus, velocityreviews, devx
No comments:
Post a Comment