Vector in STL | C++

/Vector in STL | C++

Introduction

C++ has a vector class within the std namespace. A vector is similar to an array, in a sense where a series of elements are stored with the same variable name. Unlike arrays, vectors are dynamically sized, which is a major advantage. Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

 

Syntax

// Declare vector of type 'dataType'
vector<dataType> vectorName;

// Provide size
vector<dataType> vectorName(size);

// Add an item
vectorName.push_back(value);

// Access an index
vectorName[index];

// Change value at a certain index
vectorName[index] = value;

 

Member Functions

 

  1. void push_back (const value_type& val);
    Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
  2. void pop_back();
    Removes the last element in the vector, effectively reducing the container size by one.
  3. void clear();
    Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
  4. iterator begin();
    Returns an iterator pointing to the first element in the vector.
  5. iterator end();
    Returns an iterator referring to the past-the-end element in the vector container. The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.
  6. iterator insert (iterator position, const value_type& val);
    void insert (iterator position, size_type n, const value_type& val);
    The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity. This is generally an inefficient operation.

 

Example

// Illustrate vector 
#include <iostream> 
#include <vector> 

using namespace std; 

int main() 
{
  vector<int> vec; 

  // Add elements
  for (int i = 1; i <= 5; i++) 
    vec.push_back(i); 

  // Get an iterator pointing to the first element, and traverse the vector till the last element
  for(vector<int>::iterator i = vec.begin(); i != vec.end(); i++) 
  {
    cout << *i <<" ";
  }

  // inserts 5 at the beginning 
  vec.insert(vec.begin(), 5); 

  // Removes last element 
  vec.pop_back(); 

  // Change value at index '0'
  vec[0] = 5;

  // Erases the vector 
  vec.clear(); 

  return 0; 
}

 

July 2nd, 2019|Categories: Programming|
avatar
  Subscribe  
Notify of