the stl and you
TRANSCRIPT
THE STL AND YOULeveraging the C++ Standard Template Library for great good!
A sprinkle of Thrust as well
STL
• A very large body of data structures and algorithms
•Most of the primal data structures
• Stacks, Queues, Lists, Hashmaps(C++11) and more
• Algorithms which operate on these data structures
• Partitioning, Counting, Sorting and more
STL
• Split into 4 sort of groups
• Containers
• Iterators
• Algorithms
• Functors
• Function objects
STL
• Unless you are using an extremely old compiler and libc++ you have most of it
•Newer C++11 features may or may not be implemented depending on your tool chain
• It will be noted when something is only for the new kids on the block
• Influenced the standard library
CONTAINERS
• Just kidding...
• Used to organize data in a regular way
• Sequential containers
• Associative containers
• Unordered containers(C++11)
CONTAINERS
•We will be primarily focusing on sequential containers
• Thrust provides only a single sequential container
SEQUENTIAL CONTAINERS
• std::vector
• a dynamically sized array
• std::list
• generally a doubly linked list
• std::deque
• a double ended queue
STD::VECTOR
• The container we are interested in
• Thrust provides a vector implementation for the GPU
STD::VECTOR
• Superficially very similar to a plain jane array
• foo[ idx ]
• Grows dynamically
• Reallocations tend to be 2x the previous capacity
• Presizing can be important depending on use
STD::VECTOR
• std::vector<int>
• The T in STL
• The following page is from the excellent http://en.cppreference.com/w/cpp
• Replace the en with zh for a handy Chinese reference
STD::VECTOR
•Once created add elements using push_back(ele) or insert(it, ele)
• These will cause resizing events if needed
• using foo[ idx ] = bar will not
STD::VECTOR
• Request the size of vector with size() and the capacity with capacity()
• Size(red) vs Capacity(black)
STD::VECTOR
• Iterating through the elements can be done with a for loop like the arrays you are probably used to.
• There is are better ways...
CONTAINERS
• The interface for containers is largely similar
• Take the time to get to know them
•maps and vectors probably the most used.
ITERATORS
•Many different classes
• Important when considering performance and which algorithms to use
ITERATORS
• http://en.cppreference.com/w/cpp/concept/Iterator
• an example of the requirements for a class of iterators
GETTING AN ITERATOR
• foo.begin()
• all containers except the containers built on top of other containers(stack, queue, priority_queue)
• also foo.end()
• foo.rbegin()
• foo.cbegin() foo.crbegin() (C++11)
ITERATORS
• From there you can use it!
• for( auto it = foo.begin(); it != foo.end(); ++it)
• for( auto it : foo ) (C++11)
CAVEATS
• Some functions or actions invalidate iterators
• Typically anything that could cause resizing of the container or reorder of the elements within the operator