Topic: | Data Structures (STL, Vectors, Deques) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 02, 2009 |
C++ library of commonly used data structures and algorithms.
Collection of elements of a particular type.
vector<int> mVector;
map<string, int> mMap;
list< set<double> > mListOfSets;
Templates (i.e ``<Type>``) allow customization and optimization of data structures.
mVector.push_back(12345);
mVector.clear();
mVector.size();
STL containers have 4 special iterators: begin(), end(), rbegin(), rend().
Modifying the container may invalidate iterators.
Used throughout STL, so get used to them.
Print items in a vector:
for (int i = 0; i < mVector.size(); i++)
cout << mVector[i];
vector<int>::iterator it;
for (it = mVector.begin(); it != mVector.end(); it++)
cout << *it;
copy(mVector.begin(), mVector.end(), ostream_iterator<int>(cout, " "));
Reverse a vector
reverse(mVector.begin(), mVector.end());
Reverse a string
reverse(mString.begin(), mVector.end());
Like vector but supports O(1) insertion and deletion at the beginning of container:
mDeque.push_back(1);
mDeque.push_front(2); // Not supported by vector
mDeque.pop_front(); // Not supported by vector
mDeque.pop_back();
Complete deque example.