CS 32 Lecture 10. STL

6930 단어 CS 32CC

STL Vector

The STL Vector is a template class like an array with dynamic length.

push_back(): add an element at the end of an array
empty: check if the array is empty

STL List

The STL list is a class that works like a linked list.

push_back()
push_front()

STL Iterator

How to iterate through link (not just link but other STL containers)
An iterator variable is just like a container variable but it's used just with STL containers.

container<data type>:: iterator iterator's name

You can use begin() to use to point an iterator to point at the first item.

When we use * operator with an iterator, this is called operator overloading.

end() points the last item in the container.

vector<int> myVec;

myVec.push_back(1);
myVec.push_back(2);
myVec.push_back(3);

vector<int>::iterator it;
it = myVec.end();
it--;
// now it points to the last node

You can make loops with end()

while (it != myVec.end())
{
    cout << (*it);
    it++;
}

Const iterator

To iterate through the container, you can't use the regular iterator with the container passed on as a const reference parameter.

STL Map

This works like a dictionary in python, <key, value> pair.

#include <map>
#include <string>
using namespace std;

main()
{
   map<string, int>
   name2age["Jene"] = 23;
   name2age["Antoo"] = 10;
   
   // name2age[1] = "Baby"
   // this is invalid
}

map.find(key)can be used to find a value to a corresponding key.

The map always maintains its items in alphabetical order It'll always be automatically ordered.

Using iterator in map

Map and Struct/Class


The map sorts Student by using the custom boolean operator.

STL Set

A set is a container that keeps track of unique items.
If you insert a duplicate item into the set, it is ignored.

erase() is used to delete item from the set.

As with the map, we have to define the operator to define the order of classes used as items.

.find()

.erase()

Most STL containers have an erase() method to delete an item.

Iterator then add or erase?

Once after we do add or erase, we'll need to reset the iterator by doing it = x.begin();.

STL Algorithm

sort()

In the above case, alex will not be considered.
So in order to use sort the whole array,
we have to do sort(n.begin(), n.end());

Instead of sort(arr, arr+4, &customCompare) is the same to sort(&arr[0], &arr[4], &customCompare)

좋은 웹페이지 즐겨찾기