C++ Standard Template Library

Vector

  • push_back()
  • Erase()
    • erase(int position)
    • erase(int start, int end)
vec.erase(vec.begin() + 4); // removes the 5th element

vec.erase(vec.begin() + 3, vec.begin(7)); // removes elements 4 to 8

Algorithms

#include <algorithm>
  • sort
    • sort(int start, int end)
/* Example: sorting vector v */
std::sort(v.begin(), v.end());
  • lower_bound given a sorted vector and a search value
    • std::lower_bound(int start, int end, Type value)
    • if the value exisit, return the position of the value
    • if doesn't exist, return the position of the smallest element greater than the search value
/* Example: find the position of lower bound 
            of val, in vector v */
vector<int>::iterator low = lower_bound(v.begin(), v.end(), val);
/* The index of lower bound element is: */
cout << low - v.begin() << endl;

Sets

  • Create a set set<int> s;
  • insert() s.insert(val);
  • erase() s.erase(val);
  • size() s.size();
  • find() s.find(query);
    • if found, returns the iterator to that element
    • if not found, returns s.end()
    • set<int>::iterator itr = s.find(query);

Maps

  • Template: std::map<keytype, valuetype>
  • Declaration: map<string, int> m;
  • size()
  • insert()
    • m.insert(make_pair(key, value));
  • find()
  • empty()
  • Accessing elements: m[key]

Deque (double ended queue)

  • Template: std::deque<value_type>
  • Declaration: deque<int> mydeque;
  • size()
  • Push:
    • push_back()
    • push_front()
  • pop()
    • pop_back()
    • pop_front()
  • empty()

In [ ]: