Standard Template Library Cheatsheet
Standard Template Library Cheatsheet
Creation
• Make an empty vector of integers.
vector<int> iseq1;
vector<double>(10, 50);
• Make a 100-element vector of string, double pairs, each initialized to “height”, -1.
vector<int>::iterator pos;
iseq1.size()
matrix2.size()
1
• Number of elements in the first row of a vector of vectors.
matrix2[0].size()
iseq2.front()
iseq2.back()
iseq1.begin()
• Return an iterator pointing to the imaginary position one past the end of the vector.
iseq1.end()
iseq2[5]
matrix2[7]
matrix2[7][3]
• Compute the value of an iterator pointing to the element at index 5 of the vector.
iseq1.begin() + 5
myPair.first
myPair.second
2
Insertion and Removal
• Add a integer to the end of a vector.
iseq1.push_back(20);
pseq.push_back(make_pair(string("weight"), 175.5));
iseq1.pop_back();
iseq2.insert(pseq.begin() + 5, 99);
• Append a new row of 100 elements (each set to zero) to the end of this vector of vectors.
matrix1.push_back(vector<int>(100, 0));
• Insert a new row of 55 elements (each initialized to 75) at the start of this vector of vectors.
iseq2.erase(pseq.begin());
pseq.erase(pseq.begin() + 7);
iseq2.clear();
• Empty the last row of a vector of vectors, but don’t remove it.
matrix2.back().clear();
3
Supporting Algorithms
• Print out every element of a vector.
// Using iterators
for (vector<int>::iterator pos = iseq1.begin(); pos != iseq1.end(); pos++)
cout << *pos << endl;
sort(iseq2.begin(), iseq2.end());
• Sort contents of vector of pairs, ordering by < for the first fields and using the second fields if first fields
are identical.
sort(pseq.begin(), pseq.end());
• Return an iterator pointing to the first occurrence of the value 5 in a vector. If not found, return the
given end iterator.
find(iseq1.begin(), iseq1.end(), 5)
reverse(iseq2.begin(), iseq2.end());