C++ Built-in Functions Reference
Quick reference for commonly used C++ functions
String Functions
Include: #include <string>
length() / size()
Get string length
std::string s = "Hello";
s.length(); // 5
s.size(); // 5
empty()
Check if string is empty
std::string s = "";
s.empty(); // true
substr(pos, len)
Extract substring
std::string s = "Hello World";
s.substr(0, 5); // "Hello"
s.substr(6); // "World"
find(str)
Find substring position
std::string s = "Hello World";
s.find("World"); // 6
s.find("xyz"); // string::npos
rfind(str)
Find last occurrence
std::string s = "hello hello";
s.rfind("hello"); // 6
append() / +=
Add to end of string
std::string s = "Hello";
s.append(" World");
s += "!"; // "Hello World!"
insert(pos, str)
Insert at position
std::string s = "Helo";
s.insert(3, "l"); // "Hello"
erase(pos, len)
Remove characters
std::string s = "Hello World";
s.erase(5, 6); // "Hello"
replace(pos, len, str)
Replace substring
std::string s = "Hello World";
s.replace(6, 5, "C++");
// "Hello C++"
c_str()
Get C-style string
std::string s = "Hello";
const char* c = s.c_str();
at(index) / []
Access character
std::string s = "Hello";
s[0]; // 'H' (no bounds check)
s.at(0); // 'H' (throws if out)
front() / back()
First/last character
std::string s = "Hello";
s.front(); // 'H'
s.back(); // 'o'
clear()
Remove all characters
std::string s = "Hello";
s.clear(); // ""
compare(str)
Compare strings
std::string s = "abc";
s.compare("abc"); // 0
s.compare("abd"); // -1
starts_with() (C++20)
Check prefix
std::string s = "Hello";
s.starts_with("He"); // true
ends_with() (C++20)
Check suffix
std::string s = "Hello";
s.ends_with("lo"); // true
stoi(), stol(), stod()
String to number
std::stoi("42"); // 42
std::stod("3.14"); // 3.14
std::stol("999999"); // 999999L
to_string()
Number to string
std::to_string(42); // "42"
std::to_string(3.14); // "3.140000"
Array & Vector Functions
Include: #include <vector> #include <array>
size()
Get number of elements
std::vector<int> v = {1,2,3};
v.size(); // 3
empty()
Check if empty
std::vector<int> v;
v.empty(); // true
push_back(val)
Add element at end
std::vector<int> v = {1,2};
v.push_back(3); // {1,2,3}
pop_back()
Remove last element
std::vector<int> v = {1,2,3};
v.pop_back(); // {1,2}
emplace_back(args)
Construct at end
std::vector<std::pair<int,int>> v;
v.emplace_back(1, 2);
front() / back()
First/last element
std::vector<int> v = {1,2,3};
v.front(); // 1
v.back(); // 3
at(index) / []
Access element
std::vector<int> v = {1,2,3};
v[0]; // 1 (no check)
v.at(0); // 1 (throws)
clear()
Remove all elements
std::vector<int> v = {1,2,3};
v.clear(); // {}
insert(pos, val)
Insert at position
std::vector<int> v = {1,3};
v.insert(v.begin()+1, 2);
// {1,2,3}
erase(pos)
Remove at position
std::vector<int> v = {1,2,3};
v.erase(v.begin()+1);
// {1,3}
resize(n)
Change size
std::vector<int> v = {1,2};
v.resize(5); // {1,2,0,0,0}
reserve(n)
Reserve capacity
std::vector<int> v;
v.reserve(100); // Preallocate
capacity()
Get capacity
std::vector<int> v;
v.reserve(100);
v.capacity(); // 100
shrink_to_fit()
Reduce capacity to size
std::vector<int> v = {1,2,3};
v.shrink_to_fit();
begin() / end()
Iterator to start/end
for (auto it = v.begin();
it != v.end(); ++it)
rbegin() / rend()
Reverse iterators
for (auto it = v.rbegin();
it != v.rend(); ++it)
data()
Get raw pointer
std::vector<int> v = {1,2,3};
int* p = v.data();
swap(other)
Swap contents
std::vector<int> a={1}, b={2};
a.swap(b); // a={2}, b={1}
Scroll down for Math, I/O, Algorithm, and Utility functions
Math Functions
Include: #include <cmath>
abs(x)
Absolute value
std::abs(-5); // 5
std::abs(-3.14); // 3.14
pow(base, exp)
Power function
std::pow(2, 3); // 8.0
std::pow(9, 0.5); // 3.0
sqrt(x)
Square root
std::sqrt(16); // 4.0
std::sqrt(2); // 1.414...
cbrt(x)
Cube root
std::cbrt(27); // 3.0
std::cbrt(8); // 2.0
ceil(x)
Round up
std::ceil(2.3); // 3.0
std::ceil(-2.3); // -2.0
floor(x)
Round down
std::floor(2.7); // 2.0
std::floor(-2.7); // -3.0
round(x)
Round to nearest
std::round(2.5); // 3.0
std::round(2.4); // 2.0
trunc(x)
Truncate decimal
std::trunc(2.9); // 2.0
std::trunc(-2.9); // -2.0
fmod(x, y)
Floating-point modulo
std::fmod(5.3, 2); // 1.3
max(a, b) / min(a, b)
Maximum/minimum
std::max(3, 7); // 7
std::min(3, 7); // 3
log(x) / log10(x)
Logarithm
std::log(2.718); // ~1.0
std::log10(100); // 2.0
exp(x)
e raised to power
std::exp(1); // 2.718...
sin, cos, tan
Trigonometric (radians)
std::sin(0); // 0.0
std::cos(0); // 1.0
std::tan(0.785); // ~1.0
asin, acos, atan
Inverse trig
std::asin(1); // π/2
std::acos(0); // π/2
hypot(x, y)
Hypotenuse
std::hypot(3, 4); // 5.0
isnan, isinf
Check special values
std::isnan(0.0/0.0); // true
std::isinf(1.0/0.0); // true
Input/Output Functions
Include: #include <iostream> #include <fstream> #include <iomanip>
cout <<
Output to console
std::cout << "Hello";
std::cout << 42 << "\n";
cin >>
Input from console
int x;
std::cin >> x;
getline()
Read entire line
std::string line;
std::getline(std::cin, line);
endl
Newline + flush
std::cout << "Hi" << std::endl;
setw(n)
Set field width
std::cout << std::setw(10)
<< 42; // " 42"
setprecision(n)
Set decimal precision
std::cout << std::setprecision(2)
<< 3.14159; // "3.1"
fixed / scientific
Number format
std::cout << std::fixed << 3.14;
std::cout << std::scientific;
boolalpha
Print bool as text
std::cout << std::boolalpha
<< true; // "true"
hex / dec / oct
Number base
std::cout << std::hex << 255;
// "ff"
ifstream
Read from file
std::ifstream file("data.txt");
std::string line;
std::getline(file, line);
ofstream
Write to file
std::ofstream file("out.txt");
file << "Hello";
cerr / clog
Error/log output
std::cerr << "Error!";
std::clog << "Log msg";
Algorithm Functions
Include: #include <algorithm> #include <numeric>
sort(begin, end)
Sort elements
std::vector<int> v = {3,1,2};
std::sort(v.begin(), v.end());
// {1,2,3}
reverse(begin, end)
Reverse elements
std::vector<int> v = {1,2,3};
std::reverse(v.begin(), v.end());
// {3,2,1}
find(begin, end, val)
Find element
auto it = std::find(
v.begin(), v.end(), 2);
count(begin, end, val)
Count occurrences
std::vector<int> v = {1,2,2,3};
std::count(v.begin(), v.end(), 2);
// 2
accumulate()
Sum elements
std::vector<int> v = {1,2,3};
std::accumulate(v.begin(),
v.end(), 0); // 6
max_element()
Find maximum
auto it = std::max_element(
v.begin(), v.end());
// *it is max value
min_element()
Find minimum
auto it = std::min_element(
v.begin(), v.end());
binary_search()
Search sorted container
std::vector<int> v = {1,2,3,4};
std::binary_search(
v.begin(), v.end(), 3); // true
lower_bound()
First not less than
std::vector<int> v = {1,3,5,7};
auto it = std::lower_bound(
v.begin(), v.end(), 4);
// points to 5
upper_bound()
First greater than
auto it = std::upper_bound(
v.begin(), v.end(), 3);
// points to 5
fill(begin, end, val)
Fill with value
std::vector<int> v(5);
std::fill(v.begin(), v.end(), 7);
// {7,7,7,7,7}
copy()
Copy elements
std::copy(src.begin(),
src.end(), dst.begin());
transform()
Apply function to each
std::transform(v.begin(), v.end(),
v.begin(), [](int x) {
return x * 2;
});
for_each()
Apply to each element
std::for_each(v.begin(), v.end(),
[](int x) {
std::cout << x;
});
unique()
Remove consecutive dups
std::vector<int> v = {1,1,2,2,3};
auto end = std::unique(
v.begin(), v.end());
v.erase(end, v.end());
remove_if()
Remove matching elements
auto end = std::remove_if(
v.begin(), v.end(),
[](int x) { return x < 3; });
v.erase(end, v.end());
all_of / any_of / none_of
Check predicate
std::all_of(v.begin(), v.end(),
[](int x) { return x > 0; });
// true if all positive
next_permutation()
Generate permutations
std::vector<int> v = {1,2,3};
std::next_permutation(
v.begin(), v.end());
// {1,3,2}
Utility Functions
Include: #include <utility> #include <tuple> #include <chrono>
make_pair()
Create pair
auto p = std::make_pair(1, "hi");
p.first; // 1
p.second; // "hi"
make_tuple()
Create tuple
auto t = std::make_tuple(1, 3.14, "hi");
std::get<0>(t); // 1
swap(a, b)
Swap values
int a = 1, b = 2;
std::swap(a, b); // a=2, b=1
move()
Enable move semantics
std::vector<int> a = {1,2,3};
auto b = std::move(a);
// a is now empty
tie()
Unpack tuple
int a; std::string b;
std::tie(a, b) =
std::make_tuple(1, "hi");
optional (C++17)
Optional value
std::optional<int> opt = 42;
if (opt) {
std::cout << *opt;
}
clamp() (C++17)
Clamp to range
std::clamp(15, 0, 10); // 10
std::clamp(-5, 0, 10); // 0
chrono - duration
Time measurement
auto start =
std::chrono::steady_clock::now();
// ... work ...
auto end =
std::chrono::steady_clock::now();
Memory Functions
Include: #include <memory>
make_unique() (C++14)
Create unique_ptr
auto ptr =
std::make_unique<int>(42);
make_shared()
Create shared_ptr
auto ptr =
std::make_shared<int>(42);
unique_ptr methods
Smart pointer ops
ptr.get(); // Raw pointer
ptr.reset(); // Delete
ptr.release(); // Release ownership
shared_ptr methods
Reference counting
ptr.use_count(); // Ref count
ptr.unique(); // Is sole owner?
weak_ptr
Non-owning reference
std::weak_ptr<int> weak = shared;
if (auto p = weak.lock()) {
// Use p
}
sizeof()
Size in bytes
sizeof(int); // 4
sizeof(double); // 8
sizeof(myArray); // total bytes