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]wheremis 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
autospecifies 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];,ais a pointer to an int array of size 3.
for-each loops
- The
autokeyword - 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 *arrandint 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 thatarrnot only points to anint, it points to the firstintin an array ofints.
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 = bto copy string from b to a - use
a + bto 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
intintostring: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_rangeexception 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
本文介绍了C++的基础知识,包括变量的初始化,局部变量默认带有随机值,变量大小不确定的对象需使用memset()设置。讲解了声明方式,如auto关键字用于自动类型推断,以及数组名是否等同于指针。还讨论了for-each循环的使用,特别是引用的运用。深入到函数部分,涵盖了默认参数、重载、函数模板以及类的方法,特别提到了构造函数和析构函数的作用。同时,文章探讨了字符串操作、输入/输出库、内置数据结构如数组和向量的使用,以及多维向量的处理。此外,还介绍了栈、队列、集合和哈希映射等数据结构。
1312

被折叠的 条评论
为什么被折叠?



