C ++ learning notes

Source: Internet
Author: User

After the algorithm class is over, it is estimated that C ++ will not be used in the future. I have sorted out some experience and skills in using C ++. This summary mainly references the article/website, thank you for your work! 1. @ mannhello's article: Introduction and comparison of c ++ containers 2. Author's unknown article: comparison of several containers in C ++ 3. Awesome C ++ library function Website: www.cplusplus.com. It is worth noting that I would like to express my gratitude for their work achievements again! If you find any mistakes or omissions, please be grateful! Please indicate the source for reprinting. Thank you! 1. Some tips on using C ++: (1) line breaks and spaces should be kept in mind when performing algorithm questions to avoid low-level errors; (2) When a question times out, if you are using cin/cout, first add std: ios: sync_with_stdio (false) In the first line of the main () function; cancel synchronization, if it cannot be solved, convert all the cin/cout into C-style scanf/printf; (3) when performing algorithm questions, you can use the library function for sorting: # include <algorithm> sort (); you can write a special cmp method for the size relationship of the struct to pass in. (4) The array initialization can be like this: # include <memory. h> int a [100]; memset (a, 0, sizeof (int) * 100); // assign each byte of array a to "0" memset (, 1, sizeof (int) * 100); // This is not acceptable, will put an in Each byte of t is assigned a value of "1", and the last value stored in the array is 16843009 (1 00000001 00000001 00000001). (5) for floating point comparison, you need to use one technique: a> B: a> B + (1e-6) a> = B: a> B-(1e-6) a <B: a <B-(1e-6) a <= B: when a <B + (1e-6) a = B: a> B-(1e-6) & a <B + (1e-6) (6) has high precision requirements, you can obtain: # include <math. h> pi = acos (-1, 0); (7) if you need to customize the input and output test data, you can redirect the data stream to the file: freopen ("in.txt", "r ", stdin); freopen ("out.txt", "w", stdout); then the cin/cout used will be read from the file; (8) for the mode of large numbers To avoid overflow, use this formula: (X * X % M) = (X % M * X % M) % M; (9) String Conversion number: # include <stdlib. h> char c [5]; string s; int n = atoi (c); int n = atoi (s. c_str (); // atoi () will scan the nptr parameter string. If the first character is neither a number nor a positive or negative number, return zero. Otherwise, type conversion will begin, if a non-number or Terminator/0 is detected, the conversion is stopped and the integer number is returned. Long n = atol (c); long n = atol (s. c_str); // atol () will scan the nptr parameter string and skip the leading space character until conversion starts when a number or positive or negative sign is encountered, the conversion ends only when a non-number or string ends ('/0') and the result is returned. Double n = atof (c); double n = atof (s. c_str); // atof () will scan the nptr parameter string and skip the leading space character until the conversion starts in case of a number or positive or negative sign, the conversion ends only when a non-number or string ends ('/0') and the result is returned. The nptr string can contain positive and negative numbers, decimal points, or E (e) to represent the exponential part, such as 123.456 or 123e-2. (10) For a character set combination, you can obtain its full arrangement in this way: # include <algorithm> string str; do {..... // Obtain the Next string in the full array of the current str. Use str directly.} while (next_permutation (str. begin (), str. begin () + str. length (); (11) the requirements for line breaks or spaces between two cases can be like this: bool OK = false; while (case) {if (OK) cout <endl; OK = true ;......} (12) when the question appears like "N points, N-1 side, no ring" "N points, N-1 side, any two points connected" N points, any two points of simple connection "indicates that N in the question is a tree. (13) if the complexity of a question is less than 10 ^ 8, it does not matter if it is enumerated using brute force. (14) for search, if you know the maximum number of steps, you can use DFS to obtain all paths (recursively); if you require the minimum number of steps, you can use BFS (Queue ); 2. Container 2.1 common functions and attributes of all containers 2.1.1 common typedef in containers the following typedef are commonly used to declare variables, parameters, and function return values: (1) Type of elements stored in the value_type container (2) reference container stores reference of element type (3) constant reference of element type stored in const_reference container. Such reference can only read elements in container and perform const operation (4) pointer for storing element types in the pointer container (5) iterator pointing to storing element types in the container (6) const_iterator points to the constant iterator that stores element types in the container, and can only read elements in the container (7) reverse_iterator points to the reverse iterator that stores element types in the container, this type of iterator in the container reverse iteration (8) const_reverse_iterator points to the reverse iterator that stores element types in the container, and can only read elements in the container (9) difference_type references the type of the result of two iterators subtract from the same container (list and associated containers do not define operator-) (10) size_type is used to calculate the number of items in the container and the type of the retrieval sequence container (list retrieval is not allowed) 2.1.2 all standard library common functions (except the adapter) :( 1) constructor and destructor) C <T> a; // default constructor. The Initialization is null. B) C <T> a (a0); // copy constructor to initialize the existing counterparts of similar containers. c) C <T> a (iter1, iter2); // copy the structure Create a function and initialize it to a part of the existing similar containers. d )~ C <T> (); // destructor (2) iterator a) iterator begin () notest; const_iterator begin () const notest; // return C <T>:: iterator or C <T >:: const_iterator, reference the first element of the container B) iterator end () notest; const_iterator end () const notest; // return C <T> :: iterator or C <T>: const_iterator, references a c) reverse_iterator rbegin () nothrow; const_reverse_iterator rbegin () const nothrow; // return C <T >:: reverse_iterator or C <T >:: const_reverse_iator Tor, reference the last element of the container d) reverse_iterator rend () nothrow; const_reverse_iterator rend () const nothrow; // returns C <T >:: reverse_iterator or C <T> :: const_reverse_iterator, which references the First e in front of the first element of the container) const_iterator cbegin () constnostmt; // used only for C ++ 11 and returns C <T >:: const_iterator, reference the first element of the container f) const_iterator cend () constnostmt; // used only for C ++ 11, return C <T >:: const_iterator, reference a g behind the last element of the container) const_reverse_iteratorcrbegin () const notest; // only used for C ++ 11, return C <T>: const_reverse_iterator, reference the last element of the container h) const_reverse_iterator crend () const no1_t; // only used for C ++ 11, returns C <T >:: const_reverse_iterator, referencing the first (3) function a) bool empty () const notest before the first element of the container; // if the container is empty, returns true, otherwise false B) size_type max_size () const; // returns the maximum number of elements in the container c) size_type size () const; // return the current number of elements of the container (4) Container operation function a) iterator insert (const_iteratorposition, const value_type & val); // insert data to the specified position and return The first iterator in the newly inserted data. In addition to this inserted function, there are many other overload functions B) iterator erase (const_iterator position); iterator erase (const_iterator first, const_iterator last ); // delete a specified value or a range in the container. Note: The range concept is [first, last) c) void swap (C <T> & x ); // exchange data between the current container and the incoming container x) void clear () notest; // delete all elements in the current container, also, the size is cleared to 0 2.2. sequential container 2.2.1 all sequential containers have a total of functions. The following are the functions shared by all sequential containers: (1) element access function a) reference front (); const_reference front () const; // return the reference of the first element in the container. Meaning: Unlike the in () method that returns the iterator, the returned element directly references B) reference back (); const_reference back () const; // return the reference of the last element in the container. Note: Unlike the return iterator of the end () method, it returns the direct reference of the element (2) Container operation function) void push_back (constvalue_type & val); void push_back (value_type & val); // Insert the element to the end of the container B) void pop_back (); // Delete the last element of the container 2.2.2 vector (1) using a comparison is a dynamic array, which also allocates memory in the heap and stores elements continuously with reserved memory, if the size is reduced, the memory will not be released. If the required capacity is greater than the current size, the memory will be allocated, and the last element will be operated the fastest (add and delete the last element as soon as possible ). In terms of access, access to any element is O (1), that is, constant. Therefore, vector is often used to save the content that requires frequent random access, and does not need to frequently add or delete intermediate elements. The iterator of the vector will become invalid when the memory is re-allocated (the elements it points to are no longer the same before and after the operation ). When more than capacity ()-size () elements are inserted into the vector, the memory will be re-allocated and all iterators will become invalid; otherwise, the iterator pointing to any element after the current element fails. When an element is deleted, the iterator pointing to any element after the element is deleted becomes invalid. (2) function a) void resize (size_type n); void resize (size_type n, value_type val); // Changes the container size to a new size, if n is smaller than the current size, the elements are deleted from the back of the container; otherwise, the size can be expanded to specify the initial value of the filled Element B) size_type capacity () constnoexcept; // return the size of the bucket allocated to the current container, which is not necessarily equal to the size. c) void reserve (size_type n); // specify the capacity for the current container, if n is greater than the current capacity, the capacity will be increased; otherwise, nothing will be done. d) void shrink_to_fit (); // only used for C ++ 11, hard to adjust the container capacity to the size (3) element access function a) reference operator [] (Size_typen); const_reference operator [] (size_type n) const; // equivalent to array subscript B) reference at (size_type n); const_reference at (size_type n) const; // The function is the same as the array subscript, but when the capacity is exceeded, the out_of_range exception is thrown. c) value_type * data () no1_t; const value_type * data () const no1_t; // It is only used for C ++ 11 and returns the pointer to the first element of the container. It is similar to the header pointer of an array. Its usage is also the same as that of the array header pointer 2.2.3 deque (1, it also saves content in the heap. The storage format is as follows: [heap 1] [heap 2] [heap 3]… Each heap stores several elements, and there is a pointer between the heap and the heap. It looks like a combination of list and vector. Deque allows you to quickly add or delete elements at the front or back, and then has a relatively high random access speed, but the random access speed is not as fast as the vector, because it requires internal processing of heap jump. Deque also has reserved space. Because deque does not require continuous space, the elements that can be stored are larger than those of vector. In addition, the elements of other blocks do not need to be moved before and after the elements are added, therefore, the performance is also high. Adding any element will invalidate the deque iterator. Deleting an element in the middle of deque will invalidate the iterator. When a deque header or tail deletes an element, only the iterator pointing to the element fails. (2) function a) void resize (size_type n); void resize (size_type n, value_type val); // Changes the container size to a new size, if n is smaller than the current size, the elements are deleted from the back of the container; otherwise, the size can be expanded to specify the initial value of the filled Element B) void shrink_to_fit (); // only used for C ++ 11. The size of deque can be larger than the actual number of stored elements. This method is used to forcibly adjust the memory usage to the size of the stored elements (3) element access function a) reference operator [] (size_typen); const_reference operator [] (size_type n) const; // equivalent to array subscript B) reference at (size_type n ); const_reference at (size _ Type n) const; // The function is the same as the array subscript, but when the capacity is exceeded, an out_of_range exception is thrown. (4) Container operation function a) void push_front (constvalue_type & val ); void push_front (value_type & val); // Insert the element to the first part of the container. B) void pop_front (); // Delete the element 2.2.4 list (1) of the first part of the container) using a two-way Ring linked list, elements are stored in the heap. Each element is stored in a memory, but the list has no space reserved. Therefore, each element allocated will be allocated from the memory, each time an element is deleted, the memory occupied by it is released. Because the data structure is a linked list, you cannot randomly access an element. However, it takes a constant to add or delete an element at the beginning, end, or in the middle. Adding any element will not invalidate the iterator. When an element is deleted, other iterators will not expire except the iterator pointing to the currently deleted element. (2) Container operation function a) void push_front (constvalue_type & val); void push_front (value_type & val); // Insert the element to the first position of the container B) void pop_front (); // Delete the first element of the container c) void resize (size_type n); void resize (size_type n, value_type val); // change the container size to a new size, if n is smaller than the current size, the elements are deleted from the back of the container; otherwise, the size can be expanded. You can specify the initial value of the filled elements. 2.3 join the container 2.3.1 all associated containers. Common functions (1) access Function a) const_iterator find (constvalue_type & val) const; iterator find (const value_type & val); // Find the corresponding value/key value. If it is found, return its iterator. If it cannot be found, return end () B) size_type count (constvalue_type & val) const; // find the number of specified values/key values, and return 0 or 1 c) iterator lower_bound (constvalue_type & val); const_iterator lower_bound (const value_type & val) const; or iterator lower_bound (const key_type & k); const_iterator lower_bound (const key_type & k) const; // return the first value in the container/iterator d whose key value is greater than or equal to val) iterator upper_bound (constvalue_type & val); cons T_iterator upper_bound (const value_type & val) const; or iterator upper_bound (const key_type & k); const_iterator upper_bound (const key_type & k) const; // return the first iterator in the container whose value/key value is greater than val. e) pair <const_iterator, const_iterator> pai_range (const value_type & val) const; pair <iterator, iterator> pai_range (const value_type & val); or pair <const_iterator, const_iterator> pai_range (constkey_type & k) const; pai R <iterator, iterator> pai_range (const key_type & k); // return the range of elements in the container that are equal to the input value/key value. The returned value is a pair value, its first value is lower_bound, and the second value is upper_bound 2.3.2 set (1) uses the balanced binary search tree that compares the internal data structure to the red and black trees, and stores the data in sort by key, the values must be comparable. It can be understood that set is a map with the same key and value. duplicate key values are not allowed, and elements are arranged in ascending order by default. In addition, all its operations can be completed within the O (log n) time complexity, and the efficiency is very high. If the element to which the iterator points is deleted, the iterator becomes invalid. Any other operations to add or delete elements will not invalidate the iterator. 2.3.3 multiset (1) Use comparison except that duplicate key values can be stored, and other cases are the same as set. 2.3.4 map (1) uses comparison internal elements to store in the form of <key, value> pairs. Key values cannot be repeated. By default, elements are sorted in ascending order by keys. You can assign a pair as follows: m. insert (map <string, int >:: value_type ("count", 100); or use the simpler array table symbol "[]". When reading data, you can specify an iterator iter as follows: iter-> first; iter-> second, or as follows: * iter. first; * iter. second ;. If the element to which the iterator points is deleted, the iterator becomes invalid. Any other operations to add or delete elements will not invalidate the iterator. (2) access function a) mapped_type & operator [] (const key_type & k); mapped_type & operator [] (key_type & k ); // It is used as an array, but note that once "[]" is used, if no corresponding key value exists at this time, an insert operation 2.3.5 multimap (1) will be generated, except that duplicate key values can be used for comparison. 2.4 container adapter 2.4.1 all container adapters have functions (1) function a) boolempty () const; // If the adapter is empty, true is returned; otherwise, false B is returned) size_type size () const; // return the number of existing elements in the adapter 2.4.2 stack (1) Use the comparison stack adapter, which can convert any type of sequence container into a stack, deque is generally used as a supported sequence container. The element can only be post-in-first-out (LIFO) and cannot traverse the entire stack. (2) function a) value_type & top (); const value_type & top () const; // obtain the top element of the stack, and B is not displayed) void push (const T & x); // press the element into Stack c) void pop (); // bring up the top element of the stack, without returning 2.4.3 queue (1) the comparison queue adapter can be used to convert any type of sequence container into a queue. deque is generally used as a supported sequence container. The element can only be FIFO and cannot traverse the entire queue. (2) function a) value_type & front (); const value_type & front () const; // get the queue Header element, and B is not displayed.) value_type & back (); const value_type & back () const; // get the end element of the queue. c) void push (const T & x) is not displayed. // Add the new element to the queue. d) void pop (); // bring up the first element of the queue without returning 2.4.4 priority_queue (1). It can convert any type of sequence container into a priority queue by using the comparison priority queue adapter, generally, vector is used as the underlying storage mode. Only the first element can be accessed, and the whole priority_queue cannot be traversed. The first element is always the element with the highest priority. The internal data structure is a heap. For a struct, if you want to create a heap, You can reload the symbol "<" inside or outside the struct: typedef struct Node {...... Bool operator <(const Node & in) const {return data <in. data; // large root heap (if it is applied to sort, It is sorted from small to large) return data> in. data; // small root heap (from big to small if it is applied to sort) }}; bool operator <(const Node & a, const Node & B) {return. data <B. data; // large root heap (if it is applied to sort, It is sorted from small to large) return. data> B. data; // small root heap (from large to small if it is applied to sort)} but if you want to build the maximum and minimum heap at the same time, you need to input a custom cmp structure: typedef struct Job {int prio; int age}; struct cmpBigHeap {// create a large root heap (leader with a higher priority) bool operator () (const Job &, const Job & B) {return. prio <B. prio ;}}; struct cmpSmallHeap {// create a small root heap (the leader with a low priority) bool operator () (const Job & a, const Job & B) {return. prio> B. prio ;}}; priority_queue <Job, vector <Job>, cmpBigHeap> bigHeap; priority_queue <Job, vector <Job>, cmpSmallHeap> smallHeap; (2) function) const value_type & top () const; // obtain the Element B with the highest priority in the priority queue) void push (const T & x); // Add the new element to the priority queue c) void pop (); // bring the element with the highest priority to the queue 3 input/output stream

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.