Sunday, September 6, 2009

Array vs vector

Vectors are intended to replace the C-style arrays, i.e. the static arrays:
  • Safe to pass as a parameter or assign to
  • Size increases when necessary means no memory management problem
  • Comparisons (==, < etc.) works "as it should"
vector has its own dangers, though:
  • 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:

operationarrayvector
Creationint t[10]vector<int> t(10); or
vector<int> t; (empty)
Assignmentin a loopt1 = t2
Indexingt[i]t[i] or t.at(i)
Inserting to the endnot possiblet.push_back(item)
Combiningnot possiblet1.insert(t1.end(), t2.begin(), t2.end())
Sizeprogrammer must knowt.size()
Emptyingnot possiblet.clear()
Comparisonin a loopt1 == t2 (likewise <>
Insertion to the middlenot possiblet.insert(iterator, item)
Searchingin a loopfind(t.begin(), t.end(), item)
Exchange of valuesin a loopt1.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

Previous post

Next post


No comments:

Post a Comment