C++ New Learning

C++ New Learning

Share what I have learned of C++.

Language

The basic rules of C++ Language

Initialization

  1. Local variables are initialized with random value.
  2. Variable-sized objects may not be initialized such as guests[m][m] where m 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

  1. For variables, the keyword auto specifies that the type of the variable that is being declared will be automatically deduced from its initializer.
  2. Is an array name a pointer in C?
  3. In the statement int (*a)[3];, a is a pointer to an int array of size 3.

for-each loops

  1. The auto keyword
  2. To use for-each to modify every value, you need to use reference:
    for (auto& i : array) {  // use &
      i = // some value;
    }
    

Functions

  1. default function parameters
  2. function overloading
  3. 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.
  4. function template
  5. default values are written in function declarations
  6. the notations int *arr and int 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 that arr not only points to an int, it points to the first int in an array of ints.

The main function

  1. special characters in command line arguments
    1. arguments with space need to be enclosed in double quotes. For example:
      ./greeting "Code cademy"
    2. literal double quotes in arguments need to be labeled with back slash \:
      ./greeting \"Code cademy\"

Classes

  1. Constructors
    1. If the object is created without specifying the initialization values, the default constructor will be called.
    2. To use constructor with parameters, create the object and provide required arguments:
      House green_house("Boston", 3); // Calls House(std::string, int) constructor
    3. Constructor Default Parameters
      1. 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;
        }
        
    4. Member Initializer Lists
    5. 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:
      1. if the subobject is of class type, the copy constructor for the class is used;
      2. if the subobject is an array, each element is copied, in the manner appropriate to the element type;
      3. if the subobject is of scalar type, the built-in assignment operator is used.
  2. Destructor
  3. class definition
    1. Don’t forget the semicolon at the end!
    2. We declare methods inside the class (in a header), then define the methods outside the class (in a .cpp file of the same name).
  4. inheritance
  5. polymorphism

Strings library

  1. use a = b to copy string from b to a
  2. use a + b to concatenate string a and b
    1. Note: int variables cannot be concatenated directly after a string using +.
  3. std::string is defined in header file string
  4. the easiest way to convert int into string: std::to_string(int)

Input/output library

  1. use istream& ignore (streamsize n = 1, int delim = EOF); to ignore characters in istream

C++'s Built-in Data Structures

  1. Arrays: fixed-sized collection of items of the same type
    1. 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
      
    2. 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:
      calculateDeterminantOfTheMatrix( int matrix[][123])  // 123 must be known
      
      See vectors to find how to pass a 2d array of unknown bound.
  2. Vectors: to be able to dynamically shrink and grow in size
    1. Initialization
      1. Initialization with specific value: std::vector<char> alphabet = {'a', 'b', 'c'};
      2. Initialization with specific size and value for all elements: std::vector<int> v(count, value);.
      3. Initialization of a 2d vector with specific size
    2. Vector Methods: .push_back(), .pop_back(), [], .front(), .back(), .size(), .empty()
      1. std::vector<int> a = b; // Copy assignment operator. Replaces the contents with a copy of the contents of other.
    3. 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;
      }
      
    4. use flip() to flip all bool value in a bool vector
  3. Stacks and Queues
  4. Sets: stores multiple unique elements
    1. 2 libraries:unordered_set and set
    2. initialization: std::unordered_set<int> primes({2, 3, 5, 7});
      1. 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}
    3. Set Methods: .insert(), .erase(), .count(), .size(), .empty()
  5. Hash Maps: stores multiple pairs (unique to key values)
    1. 2 libraries: unordered_map and map

    2. initialization:

      std::unordered_map<std::string, int> country_codes( 
      {{"India", 91}, 
      {"Italy", 39}});
      
      1. 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}.
        
    3. Hash Map Methods: .insert(), [], .erase(), .count(), .at(), .size(), .empty()

      1. 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 an out_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
        

Instances

  1. 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++
  2. Find all cliques of size K in an undirected graph
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值