Function template in the C++ Standard Library (std)

Here are common function templates in the C++ Standard Library (std):

Memory Management

// Smart Pointers
auto ptr1 = std::make_shared<int>(42);
auto ptr2 = std::make_unique<int>(42);

// Memory Operations
std::allocator<int> alloc;
std::allocate_shared<MyClass>(alloc, args...);

// Three main types of smart pointers in std::
std::shared_ptr   // Multiple owners (reference counted)
std::unique_ptr   // Single owner
std::weak_ptr     // Non-owning reference to shared_ptr

Compare the smart pointer with // Raw pointer (dangerous, manual management)

ControllerManagerNode* node = new ControllerManagerNode();
delete node; // Must remember to delete!

// Smart pointer (safe, automatic management)
auto node = std::make_shared();
// No need to delete - automatically managed

Algorithms (<algorithm>):

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

// Sorting
std::sort(vec.begin(), vec.end());
std::stable_sort(vec.begin(), vec.end());

// Searching
auto it = std::find(vec.begin(), vec.end(), 4);
auto it2 = std::binary_search(vec.begin(), vec.end(), 4);

// Modifying
std::transform(vec1.begin(), vec1.end(), vec2.begin(), func);
std::replace(vec.begin(), vec.end(), old_val, new_val);

Containers

// Vector operations
std::vector<int> vec;
vec.emplace_back(42);
vec.push_back(43);

// Map operations
std::map<std::string, int> map;
map.emplace("key", 42);
map.insert({"key", 42});

String operations

std::string str = "hello";
str.append(" world");
str.find("lo");
str.substr(0, 5);

Time utilities

auto now = std::chrono::system_clock::now();
auto duration = std::chrono::milliseconds(100);
std::this_thread::sleep_for(duration);

Math functions

double result1 = std::max(3.14, 2.72);
double result2 = std::min(3.14, 2.72);
double result3 = std::abs(-3.14);
double result4 = std::pow(2.0, 3.0);

Input Output (<iosteam>)

std::cout << "Output" << std::endl;
std::string input;
std::cin >> input;

Utility functions

// Pair and Tuple
auto pair = std::make_pair(1, "one");
auto tuple = std::make_tuple(1, "one", 3.14);

// Move semantics
auto ptr = std::move(old_ptr);

// Forward
template<class T>
void wrapper(T&& arg) {
    foo(std::forward<T>(arg));
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.