C++ STL
C++ STL
//major components
1.Containers
2.Algorithms
3.Iterators
4.Functors
---------------------------------------------------------
//containers -- collection of objects or primitive types
---------------------------------------------------------
* A container is a way that stored data is organized in memory
Examples
1.vector
2.List
3.deque
4.set
5.multiset
6.map
7.multimap
*offer more functonaities than arrays
*use algorithms to work with data in containers
------------------------------------------------------------------------------
//Algorithms -- functions for processing sequence of elements from containers
------------------------------------------------------------------------------
* Algorithms in the STL are procedures that are applied to containers to process
their data in various ways.
-------------------------------------------------------------
// Iterators -- Generate sequence of element from containers
-------------------------------------------------------------
* they point to elements in a container. You can increment an iterator, as you can
a pointer, so it points in turn to each element in a
container.
* Iterators are a key part of the STL because they connect algorithms with
containers.
--------------------------------------------------------
// Functors
* Function objects
* Overload the operator function call - operator()
* create objects that look like function
-------------------------------------------------------------------
// A simple example
#include <vector>
#include <algorithm>
std::vector<int> v {1,5,3};
// sort a vector
std::sort(v.begin(), v.end());
// reverse a vector
std::reverse(v.begin(),v.end());
---------------------------------------
// Types of Containers
--------------------------------------
1. Sequence containers (// maintain the order of stored elements)
. array , vector , list , forward_list , deque
2. Associative containers (// predefined order or no order)
. set , multi set , map , multi map
3. container adapters (// not support iterators)
. stack , queue , priority queue
---------------------------------------
// Types of Iterators
--------------------------------------
1. input iterators - from the container to the program
2. output iterators - from the program to the container
3. forward interators - navigate one item at a time in one direction
4. Bi-directional iterators - navigate one item at a time both directions
5. random access iterators - directly access a container item
---------------------------------------
// Types of Algorithms
--------------------------------------
. About 60 algorithms in the STL
1. non-modifying
2. modifying
-------------------------------------------------------------
//Generic Programming with macros
-------------------------------------------------------------
. Generic programming
writing code that works with a variety of types as arguments ,
as long as those argument types meet specific syntactic and
semantic requirements
1. Macros
2. Function templates
3. class templates
// macros #define
. c++ preprocessor directive
. no type information
. simple substitution
result = square(5);
result = 5*5;
-------------------------------------------------------------
//Generic Programming with function templates
-------------------------------------------------------------
// What is a C++ Template ?
. Blueprint
. function and class templetes
. Allow plugging-in any data type
. compiler generates the appropriate function/class from the blueprint
. Generic programming/meta-programming
. many times the compiler can deduce the type and the template parameter is not
needed
. Depending on the type of a and b , the compiler will figure it out
cout << max<double>(c,d);
cout << max(c,d);
.We can use almost any type we need
char a {'A'};
char b {'Z'};
cout<<max<player>(p1,p2);
func<int,double>(10,20.6);
func('A',12.4);
-------------------------------------------------------------
//Generic Programming with class templates
-------------------------------------------------------------
// what is class templete?
public :
item(string name , T value)
:name{name},value{value}
{}
string get_name() const {
return name;
-------------------------------------------------------------
//Introduction to STL containers
-------------------------------------------------------------
. data structures can store object of almost any type
. template based classes
. Each container has member functions
. some are specific to container
. others are available to all containers
. Each container has an associated header file
#include <container_type>
// containers - common
function Description
1. defaut constructors initaializes an empty container
2. overaloaded constructors initializes containers with many options
3. copy constructor initializes container as a copy of another container
4. move constructor Move existing container to new container
5. Destructor Destroys a container
6. copy assignment(operator =) copy one container to another
7. move assignment(operator =) move one containetr to another
8. size returns the number of elements in the container
-------------------------------------------------------------
//Introduction to STL Iterators
-------------------------------------------------------------
. Allows abstracting an arbitrary container as a sequence of elements
. They are objects that work like pointers by design
. Most comntainer classes can be traversed with iterators
// declaring iterators
. iterators must be declared based on container type they will iterate over
container_type::iterator_type iterator_name;
std::vector<int>::iterator it1;
std::list<string>::iteraor it2;
std::map<string , string>::iterator it3;
std::set<char>::iterator it4;
// initializing iterators
std::vector<int> vec {1,2,3};
std::vector<int>::iterator it = vec.begin();
// or
auto it = vec.begin();
auto it = suits.begin();
// other iterators
. begin() and end() -- iterator
. cbegin() and cend() -- const_iterator
. rbegin() and rend() -- reverse_iterator
. crbegin() and crend() -- const_reverse_iterator
-------------------------------------------------------------
//Introduction to STL Algorithms
-------------------------------------------------------------
. STL algorithms work on sequences of container elements
provided to them by an iterator
. STL has many common an duseful algorithms
. Many algorithms require extra information inorder to do their work
. functors (function objects )
. function pointers
. Lambda expressions (C++11)
// Iterator invalidation
. iterators point to container elements
. its possible iterators become invalid during processing
. suppose we are iterating over a vector of 10 elements
. And we clear() the vector while iterating ? what happend ?
. undefined behavior - our iterators are pointing to invalid locations
-----------------------------------------------------
// example algorithm - 1.find with primitive types
. The find algorithm tries to locate the first occurance of an element
in a container
. Lots of variations
. Returns an iterator pointing to the located element or end()
std::for_each(vec.begin(), vec.end(),
[] (int x) { cout << x * x << endl;} ) //
lambda
// 1 4 9 6
-------------------------------------------------------------
// SEQUENCE CONTAINER - 1.ARRAY
-------------------------------------------------------------
std::array (C++11)
#include <array>
. fixed size - size must be known at compile time
. direct element access
. provides access to the underlying raw array
. use instead of raw arrays when possible
. All iterators available do not invalidate
std::array -- initialization and assignment
std::array<string , 3 >stooges {
string ("larry"},
"Moe",
string("curly"}
};
arr1 = {2,4,6,8,10};
-------------------------------------------------------------
// SEQUENCE CONTAINER - 1.VECTOR
-------------------------------------------------------------
std::vector
#include <vector>
. Dynamic size
. handled automatically
. can expand and contract as needed
. elements are stored in contiguos memory as an array
. Direct element access (constant time )
. Rapid insertion and deletion at the back (constant time )
. insertion or removal of elements (linear time)
. All iterators available and may invalidate
std::vector
std::vector<int> vec {1,2,3};
front() - first element
back() - last element
vector<string> stooges {
string ("larry"},
"Moe",
string ("curly"}
};
vec1 = {2,4,6,8,10};
vec.size(); // 5
vec.capacity(); // 5
vec.max_size; // a very large number
vec.at(0); // 1
vec[1]; // 2
vec.front(); // 1
vec.back(); // 5
vec.push_back(person{"larry",18});
vec.emplace_back("larry",18}; // efficient - no moves no copies
vec1.empty(); // o false
vec1.swap(vec2); // swaps the 2 vectors
sort(vec1.begin(), vec1.end());
it = std::find(vec1.begin(), ve1.end(),4);
std::insert(it,vec2.begin(),vec2.eng());
// 1,2,10,3,10,20,30,40,50,4,5
// element access
at operator[] front back data