Showing posts with label vector. Show all posts
Showing posts with label vector. Show all posts

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


Vector

The C++ standard library offers the programmer plenty of generic data structures and algorithms that are ready for use. The programmer can concentrate on the essential and does not need to invent the wheel all over again. Just like string is dynamic and easier to use than static character strings, there is a dynamic data structure corresponding to static arrays. That is vector. vector is a part of the C++ standard library. The problems with arrays in C++:
  • They are static, i.e. the amount of elements cannot be changed without compiling the program again
  • An array cannot be copied into another away with the = operator
  • An array cannot be initialized with an another array
  • There is no way of knowing the current amount of actual elements without keeping constant score of the situation
vector makes all of the above possible and has a lot of other useful features. In practice, vector is generic, dynamic array.

In order to be able to use vector the library vector must be taken into use.

Any type of data can be put into a vector. All elements must be of the same type (just like with static arrays). vector is defined with <> notation:

vector< element_type > variable_name;

for example:

vector< int > numbers;
vector< string > names;

The vector is empty at initialization if no initial values are given:

vector< double > temperatures1( 5, 20.1 );
vector< double > temperatures2( 3 );
vector< double > temperatures3( temperatures2 );

now there are five elements in the vector temperatures1 with the value 20.1, all three elements in the vector temperatures2 have been initialized to 0.0 and the temperatures3 has the same contents as temperatures2.

Just like string, vector has its own functions.

vector <int> numbers(2,3);
//The elements in numbers are (3 3)
numbers.clear();
//numbers now empty
numbers.push_back(4);
numbers.push_back(10);
//Now the elements are (4 10)
numbers.push_back( numbers[1] );
//(4 10 10)
numbers.push_back( numbers.at( 0 ) );
//(4 10 10 4)
numbers.pop_back();
//(4 10 10)

// printing the contents
if( !numbers.empty() )
{
    unsigned int i;
    for( i = 0; i < numbers.size(); ++i )
    {
        cout << "numbers are: " << numbers[ i ] << " ";
    }
    cout << endl;
}

A vector can be assigned another vector of the same type with the = operator. Two vectors of the same type can be compared with ==, !=, <, >, <= and >= operators.

vector can be passed both as a value and a reference parameter like any ordinary variable:

vector<type> valueparam
vector<type>& referenceparam

In practice vector should always be passed as a reference parameter due to efficiency issues.

Reference: cplusplus, codesource, cppreference

Previous post

Next post