Def'n: contiguous data structure that holds series of values, all of the same type, each accessed by its position (0-index).
constexpr<array> or <vector> is preferred and avoid C-style arrayExample 1
int myArray[3];
myArray[0] = 0;
myArray[1] = 0;
myArray[2] = 0;
// also can use following methods to achieve same result as above:
int myArray[3] = { 0 }; // method 1
int myArray[3] = { }; // method 2
int myArray[3] { }; // method 3
Example 2: using initializer lists, where compiler deduces size automatically
int myArray[] { 1, 2, 3, 4 }; // compiler creates array of 4 elemetns
Example 3: partially declaring values, where remaining elements are set to zero
int myArray[3] { 2 }; // index 0 is set to 2. index 1, 2 is set to 0.
Example 1 : Older way
size_t arraySize { sizeof(myArray) / sizeof(myArray[0]) };
Example 2: using std::size() method, requires <array>, returns size_t, unsigned integer type in <cstddef>
size_t arraySize { std::size(myArray) };
array<int, 3> arr {9, 8, 7};
cout << format("Array size = {}", arr.size()) << endl;
array arr {9,8,7}; // also valid
vector automatically allocates enough memory to hold its elementvector<int> myVector { 11, 22 }; // create a vector of integers
// or you can define it like this using the fact vector supports CTAD
vecotr myVector { 11, 22 };
vector myVector don't work)first and second public data members. defined in <utility>pair <double, int> myPair { 1.23, 5 };
cout << format("{} {}", mPair.first, myPair.second);
// also supports CTAD
pair myPair { 1.23, 5 };
<optional> - holds value of a specific type or nothingnullptr, end(), -1, EOF, etc. and removes the need to write function as returning boolean, while storing actual result of function in an argument passed to the function as an output parameter optional (i.e. optional<T&> don't work - store pointer instead)optional<int> getData(bool giveIt) {
if (giveIt) return 42;
return nullopt; // or return {};
}
// use has_value() to check if optional has a value
cout << "data1.has_value = " << data1.has_value() << endl;
// if it has a value, retrieve via value() or dereferencing operator
cout << "data1.value = " << data1.value() << endl;
cout << "data1.value = " << *data1 << endl;
bad_optional_access may be thrown if empty optional, so we use value_or()cout << "data2.value = " << data2.value_or(0) << endl;
array values { 11, 22, 33 };
auto [x, y, z] { values };
structs if all non-static members are publicstruct Point { double m_x, m_y, m_z; };
Point point;
point.m_x = 1.0;
point.m_y = 2.0;
point.m_z = 3.0;
auto [x, y, z] { point };
const or references-to-const using structured bindings syntax by using auto& or const auto& instead of auto