CC++
Static Arrays
Size must be a constexpr (compile-time constant)
Lives on the stack.
T arr[SIZE]std::array<T,SIZE> arr
Dynamic Arrays
Size can be calculated during runtime
Wird auf dem Heap alloziert
T* arr = new T[n]
(delete[] arr)
make_unique<T[]>(n)
“Array List”
Dynamically resized array
std::vector<T> vec(n)
Stringsconst char *s = "abc"
char s[] = "abc"
std::string_view s("abc")
std::string s("abc")

Arrays

Arrays are a contiguous block of memory. The types of the array require a default constructor if the elements are not manually initialized.

Static Arrays

Static arrays are always allocated on the stack and have a fixed size at compile time. They also have automatic storage duration, which means they are automatically destroyed when they go out of scope.

Dynamic Arrays

Dynamic arrays are allocated on the heap and have a variable size at runtime. Because they are allocated on the heap, they have to be manually destroyed, except if they were created using make_unique or make_shared. The size of the array is not stored anywhere, so it has to be stored separately (and passed to functions if necessary).

Vectors

C++ introduced vectors, which are “enhanced” arrays. They can be resized dynamically and store their size and capacity. The behavior of vectors is similar to the one of Java’s ArrayList.

Multi-Dimensional Arrays

Strings

In C, strings are character arrays, terminated by the null character ('\0'). C also allows for initialization using string literals instead if array initializers.

Character Types

The default character type can store one byte. This is not enough for all characters, e.g. for emojis. This is why there are different character types, which can store more bytes (UTF-8, UTF-16, UTF-32).

  char c = 'a'; // 1 byte
wchar_t wc = L'ä'; // 1-4 bytes
char8_t c8 = u8'a'; // 1 byte
char16_t c16 = u'ൺ'; // 2 bytes
char32_t c32 = U'👍'; // 4 bytes

// Same goes for strings
char* cs = "Hello, World!"; // 1 byte per character
string s = "Hello, World!"; // UTF-8
wstring ws = L"Hello, World!"; // multiple bytes per character
// wchar_t* ws = L"Hello, World!"; // same as wstring
u8string s8 = u8"Hello, World!"; // UTF-8
// char8_t* s8 = u8"Hello, World!"; // same as u8string
u16string s16 = u"Hello, World!"; // UTF-16
// char16_t* s16 = u"Hello, World!"; // same as u16string
u32string s32 = U"Hello, World!"; // UTF-32
// char32_t* s32 = U"Hello, World!"; // same as u32string
  

Raw string literals

Raw string literals are string literals that are not interpreted by the compiler. They are useful for strings that contain many escape sequences.

  auto t = "abc \"def\" \\ghi\\ \n" // quote and backslash are escaped
auto s = R"(abc "def" \ghi\)" // Raw string literal, no escaping required

// If the string contains ')"' an additional delimiter can be specified to avoid errors:
auto u = R"x("(First line.\nSecond line...)")x"; // delimiter is 'x'