C++ New Learning
Share what I have learned of C++.
Language
The basic rules of C++ Language
Initialization
- Local variables are initialized with random value.
- Variable-sized objects may not be initialized such as
guests[m][m]
wherem
is an variable. Therefore,memset()
(in cstring library) should be used after the declaration of variable-sized objects to set the value as 0
Declaration
- For variables, the keyword
auto
specifies that the type of the variable that is being declared will be automatically deduced from its initializer. - Is an array name a pointer in C?
- In the statement
int (*a)[3];
,a
is a pointer to an int array of size 3.
for-each loops
- The
auto
keyword - To use for-each to modify every value, you need to use reference:
for (auto& i : array) { // use & i = // some value; }
Functions
- default function parameters
- function overloading
- Function declarations are generally stored in a header file (.hpp or .h) and function definitions (body of the function that defines how it is implemented) are written in the .cpp file. Note: Unlike with regular functions, we need to include the header file in the .cpp file where we define the class methods.
- function template
- default values are written in function declarations
- the notations
int *arr
andint arr[]
have the identical meaning when (and only when) used in a function header or function prototype. However, the array notation version (int arr[]
) symbolically reminds you thatarr
not only points to anint
, it points to the firstint
in an array ofint
s.
The main function
- special characters in command line arguments
- arguments with space need to be enclosed in double quotes. For example:
./greeting "Code cademy"
- literal double quotes in arguments need to be labeled with back slash
\
:
./greeting \"Code cademy\"
- arguments with space need to be enclosed in double quotes. For example:
Classes
- Constructors
- If the object is created without specifying the initialization values, the default constructor will be called.
- To use constructor with parameters, create the object and provide required arguments:
House green_house("Boston", 3); // Calls House(std::string, int) constructor
- Constructor Default Parameters
-
Note: Only parameters with default values are not required when calling a function. A constructor with a member initializer list rather than default parameters doesn’t mean you can omit any parameters:
#include <iostream> using namespace std; class House { private: std::string location; int rooms; public: // Constructor with default parameters House(std::string loc, int num) : location("New York"), rooms(5) { location = loc; rooms = num; } }; int main() { House default_house; // Error! No matching function for call to 'House:: House()' return 0; }
-
- Member Initializer Lists
- Copy Constructor in C++. How does copy constructor copy each member of an object: Each subobject is copied in the manner appropriate to its type:
- if the subobject is of class type, the copy constructor for the class is used;
- if the subobject is an array, each element is copied, in the manner appropriate to the element type;
- if the subobject is of scalar type, the built-in assignment operator is used.
- Destructor
- class definition
- Don’t forget the semicolon at the end!
- We declare methods inside the class (in a header), then define the methods outside the class (in a .cpp file of the same name).
- inheritance
- polymorphism
Strings library
- use
a = b
to copy string from b to a - use
a + b
to concatenate string a and b- Note: int variables cannot be concatenated directly after a string using
+
.
- Note: int variables cannot be concatenated directly after a string using
- std::string is defined in header file string
- the easiest way to convert
int
intostring
:std::to_string(int)
Input/output library
- use
istream& ignore (streamsize n = 1, int delim = EOF);
to ignore characters in istream
C++'s Built-in Data Structures
- Arrays: fixed-sized collection of items of the same type
- Note that when array-to-pointer decay is applied, a multidimensional array is converted to a pointer to its first element (e.g., a pointer to its first row or to its first plane): array-to-pointer decay is applied only once.
int a[2]; // array of 2 int int* p1 = a; // a decays to a pointer to the first element of a int b[2][3]; // array of 2 arrays of 3 int // int** p2 = b; // error: b does not decay to int** int (*p2)[3] = b; // b decays to a pointer to the first 3-element row of b int c[2][3][4]; // array of 2 arrays of 3 arrays of 4 int // int*** p3 = c; // error: c does not decay to int*** int (*p3)[3][4] = c; // c decays to a pointer to the first 3 × 4-element plane of c
- Multi-dimensional arrays are not very well supported by the built-in components of C and C++. You can pass an N-dimension array only when you know N-1 dimensions at compile time:
See vectors to find how to pass a 2d array of unknown bound.calculateDeterminantOfTheMatrix( int matrix[][123]) // 123 must be known
- Note that when array-to-pointer decay is applied, a multidimensional array is converted to a pointer to its first element (e.g., a pointer to its first row or to its first plane): array-to-pointer decay is applied only once.
- Vectors: to be able to dynamically shrink and grow in size
- Initialization
- Initialization with specific value:
std::vector<char> alphabet = {'a', 'b', 'c'};
- Initialization with specific size and value for all elements:
std::vector<int> v(count, value);
. - Initialization of a 2d vector with specific size
- Initialization with specific value:
- Vector Methods:
.push_back()
,.pop_back()
,[]
,.front()
,.back()
,.size()
,.empty()
std::vector<int> a = b; // Copy assignment operator. Replaces the contents with a copy of the contents of other.
- Multi-dimensional vector:
// passing a 2d vector int calculateDeterminantOfTheMatrix(vector<vector<int>> &matrix) { int res = 0; for (int i = 0 ; i != matrix.size() ; i++) for(int j = 0 ; j != matrix[i].size() ; j++) res += matrix[i][j]; // the same method to visit an element as arrays return res; }
- use
flip()
to flip all bool value in a bool vector
- Initialization
- Stacks and Queues
- Sets: stores multiple unique elements
- 2 libraries:unordered_set and set
- initialization:
std::unordered_set<int> primes({2, 3, 5, 7});
- Note: A set cannot contain duplicate elements. If the initializer list contains duplicate values, only one copy of the value will be kept in the set:
std::unordered_set<int> primes({2, 3, 5, 5}); // primes contains {2, 3, 5}
- Note: A set cannot contain duplicate elements. If the initializer list contains duplicate values, only one copy of the value will be kept in the set:
- Set Methods:
.insert()
,.erase()
,.count()
,.size()
,.empty()
- Hash Maps: stores multiple pairs (unique to key values)
-
2 libraries: unordered_map and map
-
initialization:
std::unordered_map<std::string, int> country_codes( {{"India", 91}, {"Italy", 39}});
- Note: A hash map cannot contain elements with duplicate keys. If the initializer list contains elements with duplicate keys, only the first element will be kept:
std::unordered_map<std::string, int> country_codes( {{"India", 91}, {"Italy", 39}, {"Italy", 27}}); // country_codes contains {"India", 91} and {"Italy", 39}.
- Note: A hash map cannot contain elements with duplicate keys. If the initializer list contains elements with duplicate keys, only the first element will be kept:
-
Hash Map Methods:
.insert()
,[]
,.erase()
,.count()
,.at()
,.size()
,.empty()
- Note: The
[]
operator will insert a new element into the hash map if the provided argument does not match the key of any element in the container. To avoid this behavior, use the.at()
method instead of[]
..at()
will throw anout_of_range
exception if there is no match:std::unordered_map<std::string, int> country_codes; country_codes["Japan"] = 81; country_codes["Turkey"] = 90; std::cout << country_codes.at("Pakistan"); // Error: out_of_range
- Note: The
-
Instances
- How do you find the index of an element in a vector?
How to find index of a given element in a Vector in C++ - Find all cliques of size K in an undirected graph