- Vectors are a kind of sequence containers
- Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements. But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.
- Accessing individual elements by their position index (constant time).
- Iterating over the elements in any order (linear time).
- Add and remove elements from its end (constant amortized time).
- Compared to arrays, they provide almost the same performance for these tasks, plus they have the ability to be easily resized. Although, they usually consume more memory than arrays when their capacity is handled automatically (this is in order to accomodate for extra storage space for future growth).
COMPARISON TO OTHER SEQUENCE CONTAINERS- DEQUEUE & LISTS
vectors are generally the most efficient in time for accessing elements and to add or remove elements from the end of the sequence. For operations that involve inserting or removing elements at positions other than the end, they perform worse than "dequeues" and "lists", and have less consistent iterators and references than "lists".
OTHER RELEVANT INFORMATION, IF YOU CARE TO READ
vectors -like all containers- have a "size", which represents the amount of elements contained in the vector. But vectors, also have a "capacity", which determines the amount of storage space they have allocated, and which can be either equal or greater than the actual "size". The extra amount of storage allocated is not used, but is reserved for the vector to be used in the case it grows. This way, the vector does not have to reallocate storage on each occasion it grows, but only when this extra space is exhausted and a new element is inserted (which should only happen in logarithmic frequence in relation with its size).
// vector::empty
# include < iostream >
# include < vector >
using namespace std;
int main ()
{
vector< int > myvector;
int sum (0);
for (int i=1;i<=10;i++) myvector.push_back(i);
while (!myvector.empty())
{
sum += myvector.back();
myvector.pop_back();
}
cout << "total: " << sum << endl;
return 0;
}
No comments:
Post a Comment