C++ cheat sheet
C++ cheat sheet

C++ cheat sheet

1. Callback functions

callback_function.hpp
#pragma once

#include <string>

// define a callback function based on a class method and call it with argument "output"
void use_callback_function(std::string output);
callback_function.cpp
#include "callback_function.hpp"
#include <string>
#include <iostream>
#include <functional>


class MyClass
{
public:
	static void mystaticfunction(std::string str)
	{
		std::cout << str << std::endl;
	}

	void mymemberfunction(std::string str)
	{
		mystaticfunction(str);
	}
};

void test(std::string str, std::function<void(std::string)> callBack = nullptr)
{
	if (callBack)
	{
		callBack(str);
	}
}

void use_callback_function(std::string output)
{
	// sample 1
	test(output, MyClass::mystaticfunction);

	// sample 2
	MyClass myClass;
	auto callBack = [&myClass](std::string str)
	{
		myClass.mymemberfunction(str);
	};
	test(output, callBack);
}

2. Asynchronous function call

futuresample.hpp
#pragma once

#include <string>

// call a function in another thread, using a std::future
std::wstring use_future(std::string filename);
future_sample.cpp
#include "futuresample.hpp"
#include <sstream>
#include <fstream>
#include <future>

class SampleReadClass
{
public:
	static std::wstring staticfunction_read(std::string filename)
	{
		std::wostringstream stream;
		stream << std::wifstream(filename).rdbuf();
		return stream.str();
	}

	std::wstring memberfunction_read(std::string filename)
	{
		return staticfunction_read(filename);
	}
};

std::wstring use_future(std::string filename)
{
	// sample 1
	std::future<std::wstring> f1 = std::async(SampleReadClass::staticfunction_read, filename);

	// sample 2
	SampleReadClass sampleReadClass;
	std::future<std::wstring> f2 = std::async([&]
	{
		return sampleReadClass.memberfunction_read(filename);
	});

	//////////////////////////////
	// do other things here...
	//////////////////////////////

	return f1.get() + f2.get();
}

3. Recursively collect all files in a directory

get_files_recursively.hpp
#pragma once

#include <list>
#include <vector>
#include <string>

// Collect all files in a directory recursively. Filter files, if extensionList contains entries, e. g. {".cpp", ".exe"}
std::list<std::string> get_files_recursively(std::string path, std::vector<std::string> extensionList={});
get_files_recursively.cpp
#include "get_files_recursively.hpp"
#include <filesystem>
#include <algorithm>

std::list<std::string> get_files_recursively(std::string basePath, std::vector<std::string> extensionList)
{
	std::list<std::string> result;
	for (std::string& strExtension : extensionList)
	{
		std::transform(strExtension.begin(), strExtension.end(), strExtension.begin(), ::tolower);
	}

	for (std::filesystem::path currentPath : std::filesystem::recursive_directory_iterator(basePath))
	{
		if (is_regular_file(currentPath))
		{
			bool isMatch = extensionList.empty();

			if (!isMatch)
			{
				std::string currentExtension = currentPath.extension().string();

				for (std::string& strExtension : extensionList)
				{
					if (currentExtension == strExtension)
					{
						isMatch = true;
						break;
					}
				}
			}

			if (isMatch)
			{
				result.emplace_back(currentPath.string());
			}
		}
	}

	return result;
}

4. Scan lists for certain elements

if_for_each_element.hpp
#pragma once

#include <vector>
#include <string>

std::string get_first_uppercase_entry(std::vector<std::string> list);
std::vector<std::string> get_all_uppercase_entries(std::vector<std::string> list);
if_for_each_element.cpp
#include "if_for_each_element.hpp"
#include <algorithm> // for std::find_if and std::count_if
#include <cctype> // for std::isupper

std::string get_first_uppercase_entry(std::vector<std::string> list)
{
	std::vector<std::string> result;

	auto pos = std::find_if(
		list.begin(),
		list.end(),
		[&](std::string entry)
		{
			size_t numberOfUpperCaseChars = std::count_if(entry.begin(), entry.end(), [](unsigned char c)
			{
				return std::isupper(c);
			});

			return numberOfUpperCaseChars == entry.length();
		});

	return pos == list.end() ? "" : *pos;
}


std::vector<std::string> get_all_uppercase_entries(std::vector<std::string> list)
{
	std::vector<std::string> result;

	std::for_each(list.begin(), list.end(), [&](std::string entry)
	{
		size_t numberOfUpperCaseChars = std::count_if(entry.begin(), entry.end(), [](unsigned char c)
		{
			return std::isupper(c);
		});

		if (numberOfUpperCaseChars == entry.length())
		{
			result.emplace_back(entry);
		}
	});

	return result;
}

5. Pause current thread

pause.hpp
#pragma once

void pause(int milliseconds);
pause.cpp
#include "pause.hpp"
#include <thread>
#include <chrono>

void pause(int milliseconds)
{
	std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}

6. Generate random numbers

random_number.hpp
#pragma once

#include <random>

int random_int_number(int min, int max);
double random_double_number(double min, double max);
random_number.cpp
#include "random_number.hpp"

std::random_device r;
std::default_random_engine rnd(r());

int random_int_number(int min, int max)
{
	return std::uniform_int_distribution<int>(min, max)(rnd);
}

double random_double_number(double min, double max)
{
	return std::uniform_real_distribution<double>(min, max)(rnd);
}

7. Read file into string

read_file_into_string.hpp
#pragma once

#include <string>

std::wstring read_file_into_wstring(std::string filename);
std::string read_file_into_string(std::string filename);
read_file_into_string.cpp
#include "read_file_into_string.hpp"
#include <sstream>
#include <fstream>

std::wstring read_file_into_wstring(std::string filename)
{
	std::wostringstream stream;
	stream << std::wifstream(filename).rdbuf();

	return stream.str();
}

std::string read_file_into_string(std::string filename)
{
	std::ostringstream stream;
	stream << std::ifstream(filename).rdbuf();

	return stream.str();
}

8. Search for patterns in strings

regex.hpp
#pragma once

#include <vector>
#include <tuple>
#include <string>

// return a list of the list of submatches of regex in input
std::vector<std::vector<std::string>> getMatches(std::string input, std::string regex);

std::vector<std::string> getFirstMatch(std::string content, std::string pattern);
regex.cpp
#include "regex.hpp"
#include <regex>

std::vector<std::vector<std::string>> getMatches(std::string content, std::string pattern)
{
	std::vector<std::vector<std::string>> result;
	std::regex regex(pattern);

	std::for_each(std::sregex_iterator(content.begin(), content.end(), regex), std::sregex_iterator(), [&](std::smatch match)
	{
		std::vector<std::string> subMatches;
		for (std::string subMatch : match)
		{
			subMatches.emplace_back(subMatch);
		}
		result.emplace_back(subMatches);
	});

	return result;
}

std::vector<std::string> getFirstMatch(std::string content, std::string pattern)
{
	std::vector<std::string> subMatches;
	std::smatch match;

	if (std::regex_search(content, match, std::regex(pattern)))
	{
		for (std::string subMatch : match)
		{
			subMatches.emplace_back(subMatch);
		}
	}

	return subMatches;
}

9. Multi threading

start_thread.hpp
#pragma once

#include <cstdint>

std::int64_t startAndStopThread(int runningMilliseconds, int incrementValue);
start_thread.cpp
#include "start_thread.hpp"
#include <atomic>
#include <thread>

class SampleThreadClass
{
public:
	void threadFunction(int inputVal)
	{
		while (running)
		{
			result += inputVal;
		}
	}

	std::atomic<bool> running{true};
	int64_t result{0};
};



int64_t startAndStopThread(int runningMilliseconds, int incrementValue)
{
	SampleThreadClass sampleThreadClass;

	// start thread
	std::thread t = std::thread(&SampleThreadClass::threadFunction, &sampleThreadClass, incrementValue);

	// wait
	std::this_thread::sleep_for(std::chrono::milliseconds(runningMilliseconds));

	// stop thread
	sampleThreadClass.running = false;
	t.join();

	return sampleThreadClass.result;
}

10. Thread safe function

thread_safe_function.hpp
#pragma once

#include <string>

void thread_safe_function(std::string str);
thread_safe_function.cpp
#include "thread_safe_function.hpp"
#include <string>
#include <iostream>
#include <mutex>

std::mutex mtx;

void thread_safe_function(std::string str)
{
	std::lock_guard<std::mutex> lck(mtx);

	std::cout << str << std::endl;
}

11. Write string to file

write_string_to_file.hpp
#pragma once

#include <string>

void write_string_to_file(std::string filename, std::string content);
write_string_to_file.cpp
#include "write_string_to_file.hpp"
#include <sstream>
#include <fstream>

void write_string_to_file(std::string filename, std::string content)
{
	std::ofstream(filename) << content;
}

12. Convert wstring to string

wstring_to_string.hpp
#pragma once

#include <string>

std::string to_string(std::wstring str);
wstring_to_string.cpp
#include "wstring_to_string.hpp"

std::string to_string(std::wstring str)
{
	return std::string(str.begin(), str.end());
}

13. Get path to temp directory

temp_directory.hpp
#pragma once

#include <string>

std::string get_temp_directory();
#include "temp_directory.hpp"
#include <filesystem>

std::string get_temp_directory()
{
	return std::filesystem::temp_directory_path().string();
}