0% found this document useful (0 votes)
3 views

CPP_STL (1)

Cpp stl

Uploaded by

Rajesh Pandit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CPP_STL (1)

Cpp stl

Uploaded by

Rajesh Pandit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

The C++ Standard Library (STL) is a collection of template classes and functions that provide

general-purpose tools to handle data structures, algorithms, and iterators. It is divided into
several components, each serving a different purpose. Below, I’ll provide an overview of each
key component of the STL, along with its details and functions.

1. Containers

Containers are objects that store collections of data. The STL provides different types of
containers based on their structure and usage.

Types of Containers:

• Sequence Containers: Store data in a linear order.


o vector
o deque
o list
o forward_list
o array
• Associative Containers: Store data in a sorted or unique key order.
o set
o map
o multiset
o multimap
• Unordered Containers: Store data in an unordered fashion, using hash tables.
o unordered_set
o unordered_map
o unordered_multiset
o unordered_multimap
• Container Adapters: Provide a different interface for existing containers.
o stack
o queue
o priority_queue

2. Iterators

Iterators are used to access elements in a container. They are similar to pointers and provide an
interface to traverse through the elements of containers.

Types of Iterators:

• Input Iterators: Read data in one direction (e.g., istream_iterator).


• Output Iterators: Write data in one direction (e.g., ostream_iterator).
• Forward Iterators: Can read and write data in one direction (e.g., list::iterator).
• Bidirectional Iterators: Can move both forward and backward (e.g., set::iterator).
• Random Access Iterators: Can access any element (e.g., vector::iterator).

Iterator Functions:
• begin() / end() – Returns iterators to the first and one past the last element.
• rbegin() / rend() – Returns reverse iterators (iterates backward).
• advance() – Moves an iterator forward or backward.
• distance() – Computes the distance between two iterators.
• next() / prev() – Returns the next or previous iterator.

3. Algorithms

STL provides many built-in algorithms for operations on containers and iterators.

Some Common Algorithms:

• Sorting: sort(), stable_sort()


• Searching: find(), binary_search(), lower_bound(), upper_bound()
• Modifying: reverse(), rotate(), swap()
• Partitioning: partition(), stable_partition()
• Set operations: set_union(), set_intersection(), set_difference()
• Counting: count(), count_if()
• Accumulate: accumulate(), inner_product()
• Transform: transform()
• For_each: for_each()

Example Usage:

cpp
Copy code
#include <algorithm>
#include <vector>
#include <iostream>

std::vector<int> vec = {1, 3, 2, 5, 4};


std::sort(vec.begin(), vec.end());

4. Functors (Function Objects)

Functors are objects that can be called as if they are functions. They are often used with
algorithms to customize behavior.

Example of a Functor:

cpp
Copy code
struct MultiplyBy {
int factor;
MultiplyBy(int f) : factor(f) {}
int operator()(int x) { return x * factor; }
};

std::vector<int> vec = {1, 2, 3, 4};


std::transform(vec.begin(), vec.end(), vec.begin(), MultiplyBy(2));

5. Memory Management

STL provides mechanisms to manage dynamic memory and allocate resources efficiently.

Key Features:

• allocator: Allows you to allocate memory dynamically.


• auto_ptr (deprecated in C++11): A simple pointer wrapper for automatic memory
management.
• unique_ptr: A smart pointer that manages a dynamically allocated object and deletes it
when it goes out of scope.
• shared_ptr: A reference-counted smart pointer.
• weak_ptr: A smart pointer that doesn't affect the reference count.

6. String Handling

The STL provides a string class for working with strings efficiently.

Key String Functions:

• size() / length() – Returns the length of the string.


• empty() – Checks if the string is empty.
• at() / operator[] – Accesses characters at a given position.
• append() – Adds characters to the end.
• insert() – Inserts characters at a specific position.
• erase() – Removes characters from the string.
• find() – Finds a substring.
• replace() – Replaces parts of a string.
• substr() – Extracts a substring.

cpp
Copy code
std::string str = "Hello, world!";
str.append(" Welcome!");
str.replace(7, 5, "C++");

7. Pair
std::pair is a simple container to store two values, which can be of different types.

Key Functions:

• first – The first value in the pair.


• second – The second value in the pair.
• make_pair() – A helper function to create a pair.

cpp
Copy code
std::pair<int, std::string> p = std::make_pair(1, "hello");
std::cout << p.first << " " << p.second;

8. Utility Functions

Some utility functions are provided for working with containers and algorithms.

Common Utility Functions:

• swap() – Swaps two values or containers.


• make_pair() – Constructs a pair object.
• tie() – Creates a tuple reference for unpacking values.

9. Exception Handling in STL

STL uses exceptions to indicate errors. Some standard exceptions are:

• out_of_range – Thrown when accessing out-of-bounds elements.


• invalid_argument – Thrown when a function is called with invalid arguments.
• length_error – Thrown when trying to exceed the maximum size of a container.

Example of exception handling:

cpp
Copy code
try {
std::vector<int> v = {1, 2, 3};
std::cout << v.at(10);
} catch (const std::out_of_range& e) {
std::cout << "Error: " << e.what();
}

10. Iterators with Algorithms


Many STL algorithms can be used with iterators for better flexibility.

cpp
Copy code
std::vector<int> vec = {1, 2, 3, 4, 5};
auto result = std::find(vec.begin(), vec.end(), 3);
if (result != vec.end()) {
std::cout << "Found: " << *result;
}

Summary

The STL is an essential part of modern C++ development, and it provides a wide variety of tools
to handle collections of data, algorithms, and iterators. These tools enable developers to write
cleaner, faster, and more efficient code.

To master STL, understanding the core concepts and familiarizing yourself with common
functions in containers, iterators, and algorithms is key.

You said:

give me cpp STL notes with average explanation


ChatGPT said:

ChatGPT

Here’s a concise guide with average-level explanations for the most important components of the
C++ Standard Library (STL). This guide will cover containers, iterators, algorithms, and other
important elements.

1. Containers

Containers are classes that store collections of objects. They provide built-in functions to
manage, access, and modify data efficiently.

Types of Containers:

• Sequence Containers: Store elements in a linear order.


o vector: A dynamic array that grows as needed. Random access is fast, but
inserting or deleting elements in the middle is slow.
o deque: A double-ended queue that allows fast insertions and deletions at both
ends, but random access is slower than vector.
o list: A doubly linked list. Insertion and deletion at both ends are fast, but
accessing elements randomly is slow.
o array: A fixed-size array. It’s a modern replacement for C-style arrays, offering
more safety features like size checks.
• Associative Containers: Store elements in sorted order based on a key.
o set: A collection of unique elements sorted in ascending order.
o map: A collection of key-value pairs where keys are unique and automatically
sorted.
o multiset: Like a set, but allows duplicate elements.
o multimap: Like a map, but allows duplicate keys.
• Unordered Containers: Store elements in an unordered manner using hash tables.
o unordered_set: A set where elements are stored based on a hash function,
allowing fast lookups.
o unordered_map: A map with unordered key-value pairs, implemented using hash
tables.
o unordered_multiset and unordered_multimap are similar to unordered_set
and unordered_map, respectively, but allow duplicates.
• Container Adapters: Provide a different interface to an underlying container.
o stack: Implements a Last In First Out (LIFO) data structure. It’s built on top of a
container like deque or vector.
o queue: Implements a First In First Out (FIFO) data structure.
o priority_queue: A queue where elements are ordered by priority, with the
highest priority element being processed first.

2. Iterators

Iterators provide a way to access elements in a container. They are similar to pointers but work
with STL containers in a uniform way.

Types of Iterators:

• Input Iterator: Used for reading data from a container (e.g., istream_iterator).
• Output Iterator: Used for writing data to a container (e.g., ostream_iterator).
• Forward Iterator: Can be used to read and write data in one direction (e.g.,
list::iterator).
• Bidirectional Iterator: Can move both forward and backward through a container (e.g.,
set::iterator).
• Random Access Iterator: Supports moving both forward and backward, and allows
direct access to any element (e.g., vector::iterator).

Common Iterator Functions:

• begin() / end():Return iterators to the first element and one past the last element,
respectively.
• advance(): Moves an iterator forward or backward by a specified number of steps.
• distance(): Calculates the number of steps between two iterators.
• next() / prev(): Return the next or previous iterator.

3. Algorithms

STL algorithms perform operations on containers or iterators. They make it easy to manipulate
data without needing to implement common tasks manually.

Common Algorithms:

• sort(): Sorts elements in ascending order.


• reverse(): Reverses the order of elements.
• find(): Finds the first occurrence of a value in a container.
• count(): Counts the occurrences of a value in a container.
• accumulate(): Computes the sum of a range of elements.
• transform(): Applies a function to each element in a range.
• binary_search(): Checks if an element is present in a sorted container.
• lower_bound() / upper_bound(): Finds the first position where an element can be
inserted without violating the order.

Example:

cpp
Copy code
#include <algorithm>
#include <vector>
#include <iostream>

std::vector<int> vec = {3, 1, 4, 1, 5};


std::sort(vec.begin(), vec.end()); // Sort the vector
for (int i : vec) {
std::cout << i << " "; // Output: 1 1 3 4 5
}

4. String Handling

The std::string class is part of STL and allows for dynamic string handling, unlike C-style
character arrays.

Common String Functions:

• size() / length(): Returns the number of characters in the string.


• empty(): Checks if the string is empty.
• append() / push_back(): Adds characters to the end of the string.
• insert(): Inserts characters at a specified position.
• erase(): Removes characters from a string.
• find(): Finds a substring in the string.
• substr(): Extracts a substring from the string.

Example:

cpp
Copy code
std::string str = "Hello";
str.append(" World"); // str becomes "Hello World"
std::cout << str.find("World") << std::endl; // Output: 6

5. Pair

std::pair is a simple container that stores two related values, which may be of different types.

Common Functions:

• first: The first element of the pair.


• second: The second element of the pair.
• make_pair(): A function that creates a pair.

Example:

cpp
Copy code
std::pair<int, std::string> p = std::make_pair(1, "apple");
std::cout << p.first << " " << p.second; // Output: 1 apple

6. Smart Pointers

Smart pointers automatically manage memory, reducing the risk of memory leaks.

• unique_ptr: A smart pointer that owns a dynamically allocated object and deletes it
when it goes out of scope.
• shared_ptr: A reference-counted smart pointer that allows multiple pointers to share
ownership of an object.
• weak_ptr: A pointer that holds a non-owning reference to an object managed by
shared_ptr.

Example:

cpp
Copy code
std::unique_ptr<int> ptr = std::make_unique<int>(10);
// Automatically deletes the object when ptr goes out of scope
7. Function Objects (Functors)

A functor is an object that can be called as if it were a function. This is useful when you need to
pass behavior (like a function) to algorithms.

Example:

cpp
Copy code
struct Add {
int operator()(int a, int b) {
return a + b;
}
};
Add add;
std::cout << add(2, 3); // Output: 5

8. Exception Handling

STL containers and algorithms often throw exceptions in error situations.

• std::out_of_range: Thrown when accessing an element out of range.


• std::invalid_argument: Thrown when an argument is invalid.
• std::length_error: Thrown when a container exceeds its maximum size.

Example:

cpp
Copy code
try {
std::vector<int> vec = {1, 2, 3};
std::cout << vec.at(5); // This will throw an out_of_range exception
} catch (const std::out_of_range& e) {
std::cout << "Caught exception: " << e.what();
}

9. Utility Functions

• swap(): Swaps the values of two variables or containers.


• make_pair(): Creates a pair from two values.
• tie(): Used for unpacking tuple-like objects.

Example of swap:

cpp
Copy code
int a = 10, b = 20;
std::swap(a, b); // Now a is 20 and b is 10

Summary

The C++ Standard Library (STL) is a powerful feature that provides built-in support for
containers, algorithms, iterators, and utilities. By mastering the STL, you can write more
efficient, readable, and maintainable C++ code. The main components to focus on are:

• Containers (for storing data)


• Iterators (for accessing data)
• Algorithms (for manipulating data)
• Function objects (for passing behavior)

You said:

give me cpp stl container with its functions


ChatGPT said:

ChatGPT

Here’s a detailed guide to the C++ Standard Library (STL) Containers with the key functions
for each container. This guide covers both sequence and associative containers, and their
relevant functions.

1. Sequence Containers

Sequence containers store elements in a linear order and provide functions for manipulating
those elements.

1.1 vector

A vector is a dynamic array that allows random access to its elements.

• Constructor:
o vector(): Default constructor.
o vector(size_t n): Initializes n elements with default values.
o vector(size_t n, const T& value): Initializes n elements with a specified
value.
o vector(const vector& other): Copy constructor.
• Common Functions:
o size(): Returns the number of elements.
o empty(): Returns true if the container is empty.
o at(i): Accesses element at index i, throws out_of_range if i is invalid.
o operator[]: Accesses element at index i without bounds checking.
o push_back(const T& value): Adds an element at the end.
o pop_back(): Removes the last element.
o insert(iterator pos, const T& value): Inserts an element before the
specified position.
o erase(iterator pos): Removes the element at the specified position.
o clear(): Removes all elements.
o resize(size_t n): Resizes the vector to contain n elements.
o reserve(size_t n): Allocates memory for at least n elements.

1.2 deque

A deque (double-ended queue) allows fast insertions and deletions at both ends.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the deque is empty.
o at(i): Accesses the element at index i, throws out_of_range if invalid.
o operator[]: Accesses element at index i without bounds checking.
o push_back(const T& value): Adds an element to the back.
o push_front(const T& value): Adds an element to the front.
o pop_back(): Removes the last element.
o pop_front(): Removes the first element.
o insert(iterator pos, const T& value): Inserts an element before the
position.
o erase(iterator pos): Removes the element at the specified position.

1.3 list

A list is a doubly linked list where elements can be inserted or deleted anywhere in constant
time.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the list is empty.
o front(): Returns the first element.
o back(): Returns the last element.
o push_front(const T& value): Adds an element to the front.
o push_back(const T& value): Adds an element to the back.
o pop_front(): Removes the first element.
o pop_back(): Removes the last element.
o insert(iterator pos, const T& value): Inserts an element before the
specified position.
o erase(iterator pos): Removes the element at the specified position.
o clear(): Removes all elements.

1.4 forward_list

A forward_list is a singly linked list, which is more memory-efficient than list but only
allows forward traversal.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the list is empty.
o push_front(const T& value): Adds an element to the front.
o pop_front(): Removes the first element.
o insert_after(iterator pos, const T& value): Inserts an element after the
position.
o erase_after(iterator pos): Removes the element after the position.
o clear(): Removes all elements.

1.5 array

An array is a fixed-size container that encapsulates a static array with extra functionality.

• Common Functions:
o size(): Returns the number of elements (constant time).
o at(i): Accesses the element at index i with bounds checking.
o operator[]: Accesses element at index i without bounds checking.
o front(): Returns the first element.
o back(): Returns the last element.
o fill(const T& value): Fills the array with the specified value.

2. Associative Containers

Associative containers store data in a specific order based on keys (for map, set) or allow
multiple occurrences of keys (for multimap, multiset).

2.1 set

A set is a container that stores unique elements in a sorted order (by default in ascending order).

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the set is empty.
o insert(const T& value): Adds an element to the set.
o erase(const T& value): Removes an element.
o find(const T& value): Returns an iterator to the element if found.
o clear(): Removes all elements.
o count(const T& value): Returns 1 if the element is present, otherwise 0.

2.2 map

A map stores key-value pairs, with each key being unique. The keys are automatically sorted.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the map is empty.
o insert(const std::pair<Key, T>& value): Inserts a key-value pair.
o erase(const Key& key): Removes the element with the specified key.
o find(const Key& key): Returns an iterator to the key-value pair if found.
o operator[]: Accesses or inserts a key-value pair.
o clear(): Removes all elements.

2.3 multiset

A multiset is a set that allows duplicate elements, stored in a sorted order.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the multiset is empty.
o insert(const T& value): Adds an element to the multiset.
o erase(const T& value): Removes all occurrences of a specific element.
o find(const T& value): Returns an iterator to one of the elements if found.
o count(const T& value): Returns the number of occurrences of the element.

2.4 multimap

A multimap stores key-value pairs, but unlike map, it allows multiple values with the same key.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the multimap is empty.
o insert(const std::pair<Key, T>& value): Inserts a key-value pair.
o erase(const Key& key): Removes all pairs with the specified key.
o find(const Key& key): Returns an iterator to the key-value pair if found.
o count(const Key& key): Returns the number of pairs with the specified key.

3. Unordered Containers
Unordered containers store data in an unordered fashion using hash tables.

3.1 unordered_set

An unordered_set stores unique elements in an unordered manner.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the unordered set is empty.
o insert(const T& value): Inserts an element into the set.
o erase(const T& value): Removes an element.
o find(const T& value): Returns an iterator to the element if found.
o count(const T& value): Returns 1 if the element is present, otherwise 0.

3.2 unordered_map

An unordered_map stores key-value pairs in an unordered manner.

• Common Functions:
o size(): Returns the number of elements.
o empty(): Checks if the unordered map is empty.
o insert(const std::pair<Key, T>& value): Inserts a key-value pair.
o erase(const Key& key): Removes the pair with the specified key.
o find(const Key& key): Returns an iterator to the key-value pair if found.
o operator[]: Accesses or inserts a key-value pair.

3.3 unordered_multiset

An unordered_multiset is like an unordered_set, but allows duplicate elements.

3.4 unordered_multimap

An unordered_multimap is like an unordered_map, but allows multiple key-value pairs with


the same key.

4. Container Adapters

Container adapters provide different interfaces to underlying containers.

4.1 stack

A stack implements a LIFO (Last In First Out) data structure.


• Common Functions:
o push(const T& value): Adds an element to the top.
o pop(): Removes the top element.
o top(): Returns the top element.
o empty(): Checks if the stack is empty.
o size(): Returns the number of elements.

4.2 queue

A queue implements a FIFO (First In First Out) data structure.

• Common Functions:
o push(const T& value): Adds an element to the back.
o pop(): Removes the front element.
o front(): Returns the front element.
o back(): Returns the back element.
o empty(): Checks if the queue is empty.

4.3 priority_queue

A priority_queue stores elements such that the highest priority element is always at the top.

• Common Functions:
o push(const T& value): Adds an element to the queue.
o pop(): Removes the highest-priority element.
o top(): Returns the highest-priority element.
o empty(): Checks if the priority queue is empty.
o size(): Returns the number of elements.

These are the key C++ STL containers along with their core functions. Each container is
optimized for certain types of operations, so it's important to choose the right container
depending on your needs.

ChatGPT can make mistakes. Check im

You might also like