"C + + Primer" Part II: C + + standard library

Source: Internet
Author: User
Tags arithmetic

"C + + Primer" Part II: C + + standard library

Objective

Read the "C + + Primer" Reading a series of notes. This article is part II of the C + + standard library, including the 8th to 12th chapter of the book The Difficult points:

    1. IO Library
    2. Sequential container
    3. Model algorithm
    4. Associative containers
    5. Dynamic memory

See the GitHub warehouse Cpp-primer-workbook after the revised course.

IO Library
    1. Io class inheritance mechanism: Ifstream and istringstream inherit from Istream,ofstream and Ostringstream inherit from Ostream
    2. Wide character Io class: prefix the function and type with W, such as Wcin, Wistream
    3. No copy assignment of Io object: The function of IO operation is usually passed and returned by reference; The reference to the IO object cannot be const because the read-write changes State
    4. Condition State: Iostate represents the type of stream state, which contains 4 constexpr values, Badbit (stream crash), Failbit (recoverable error), Goodbit, eofbit, corresponding 4 function bad (), fail (), good (), EOF ()
    5. Manage condition Status: Rdstate () Get status, clear () Clears all error flag bits, clear (flags) and SetState (flags) set status to Flags
    6. Flush output buffers: You can use the operator Endl (newline), flush, ends (null character), turn on unitbuf each call flush,nounitbuf dismiss
    7. Correlation Flow: An interactive system typically associates input and output streams so that all outputs are printed before the read operation; Each stream is associated with at most one stream, but multiple streams can be associated to the same ostream; associating them to a null pointer can completely unlock the association
    8. FStream: Open () opening the file-bound stream, close () closing the binding file, successful opening of the file, and Is_open () not yet closed
    9. StringStream unique: Str (s) that copies s to the StringStream object, returns a copy of the saved string str ()
Sequential container
  1. Select containers: Standard library container performance is generally better than similar data structures; the C + + standard adds array arrays and forward_list one-way lists; lots of small elements and extra space overhead, no list or forward_list
  2. Additional Operations for containers: iterator represents iterator type, size_type unsigned integer, value_type refers to element type, reference and value_type& equivalent
  3. Size operation: Returns the number of elements in the container; forward_list no size operation, the size operation of the other container is a constant time
  4. Reverse container: reverse_iterator An iterator addressed in reverse order, Rbegin () is a tail iterator, crend () represents a const first-forward iterator,
  5. Forward_list: Reverse container iterator not supported and its iterator does not support decrement operation
  6. Container initialization: Must be the same container type and save elements of the same type
  7. Initialize with size: Only the constructor of the sequential container accepts the size parameter, and the associated container does not support
  8. Array: Has a fixed size, the number of list initializations must be equal to or less than the size of the array; curly braces list can only initialize cannot be assigned value
  9. Assign: Only sequential container support, the iterator passed to assign cannot point to the container that calls assign; causes an iterator, reference, pointer invalidation to point to the container;
  10. Swap: In addition to array, swap does not copy, delete, and insert any elements to ensure constant time is complete; iterators, references, and pointers to other containers do not expire after the swap except string
  11. Relational operators: Operands on both sides must be of the same container type and hold elements of the same type
  12. Insert element: An iterator that returns the newly added first element, inserts an element into a vector, string, deque, invalidates a pointed iterator, reference, pointer, or inserts an element in the range represented by the iterator and cannot point to the same container as the destination
  13. An element is a copy: When you initialize or insert a container with an object, you actually put a copy, and the element in the container is not associated with the object that provides the value
  14. Access elements: the at and subscript operations only support string, vector, deque, array; the Access member function returns a reference
  15. Delete element: Clear and Pop return Void,erase returns an iterator that points to the element after the last deleted element
  16. Special Forward_list operation: Add or remove by changing the element after the given element to complete, define the first front iterator before_begin (); Insert_after () returns the iterator that points to the last inserted element; Erase_after () Returns an iterator that points to the element following the deleted element
  17. Change the container size: Resize () can be used to increase or decrease the container, the extra element is removed, and the specified value or default initializer object is filled.
  18. Iterator invalidation: Adding or removing elements may invalidate pointers, references, iterators that point to container elements

    add element Delete element
    Vector, string The storage space is not reassigned, then the insertion position is invalidated; Deleted elements and subsequent invalidation
    Deque Only iterators expire at the end of the add-in; Delete the first element only the first element is invalid, the tail element is deleted after the end of the iterator is also invalid;
    List, forward_list does not affect Only deleted elements are affected
  19. Do not save tail iterator: Insert Delete deque, string, vector element in loop, should call end () every time
  20. Manage container size: Capacity () returns the size of the container's reserved memory, the empty container returns 0;reverse () only increases the container's reserved memory size; Reduces the amount of space available shrink_to_fit () requests the space value to be reduced to the number of elements, but does not guarantee that the memory space must be returned
  21. Reallocate Memory: If size and capacity are equal when the insert is executed, or if resize, reserve a given size exceeds capacity,vector, the new memory space will be allocated, depending on the underlying implementation
  22. Modify the parameters that are allowed by string:replace and insert args depend on how range range and location POS are specified
  23. String::npos:string the static member returned by the search failure, the type is const String::size_type, initialized to-1
  24. String search: Find () first occurrence, rfind () Last occurrence, find_first_of () The first occurrence of any character in the parameter (), Find_last_not_of () The last occurrence of a character in a non-argument; Not found return NPOs
  25. String numeric conversions: s=to_string(val); val = stoi(s, p, b); Val can be any arithmetic type, the corresponding Stoi function is replaced with STOL, Stod, and so on, p represents the index at which the string starts to convert, and B represents the cardinality used for the conversion
  26. Container adapter: The container adapter accepts an existing container type so that its behavior looks like a different type
  27. Underlying container: Stack and queue default based on Deque,priority_queue vector-based, cannot use an array that cannot add deleted elements, or cannot access the forward_list of the tail element as the underlying container Stack can be constructed with any container other than array and forward_list, and queue may use list or Deque,priority_queue to be based on a vector or deque
  28. Adapter operation: Each adapter defines its own special action based on the operation of the underlying container type, only using the adapter operation, not using the underlying container operation
Model algorithm
  1. Model algorithm: Implements the common interface of some classical algorithms, can be used for different types of elements, multiple types of containers, other types of sequences
  2. Iterators and algorithms: The algorithm works on the iterator, which makes the algorithm independent of the container, but relies on the operation of the element type; the algorithm never performs container operations, so it does not change the size of the underlying container
  3. Input range: The standard library algorithm typically operates on a range of elements, with two iterator parameters representing left closed right open intervals
  4. Algorithm classification: Whether to read elements, change elements, rearrange element order
  5. Read-only algorithm: read without changing the element, preferably with a const iterator; If you plan to change the value of an element by using an iterator returned by the algorithm, you pass the very constant parameter
  6. Write algorithm: The algorithm does not check the write operation, all assume that the destination space is large enough, common errors have fill_n or other write operations on the empty container just defined, and ensure that the algorithm has enough element space to accommodate the output available insert iterator
  7. Iterator parameters: Some algorithms read two sequences, do not require strict matching of container or element type, only require elements in two sequences to compare
  8. Copy algorithm: Copy returns the value of the destination iterator (increment), multiple algorithms provide a "copy" version, accept an additional purpose iterator parameter, copy the new sequence to the inside without altering the sequence of the original input range
  9. Reflow algorithm: The way to remove duplicate elements of a container is to first call the rearrangement algorithm sort and unique, and then use the container to manipulate erase
  10. Custom actions: The algorithm uses the < or = = Operator By default, but allows us to pass any type of callable object, using custom actions instead of the default operator
  11. Callable objects: Functions, function pointers, classes that overload the function call (), lambda expressions
  12. predicate: Returns a function that can be converted to bool, typically used to determine an element relationship, divided into a unary predicate and a two-tuple predicate based on the number of accepted parameters
  13. Lambda expression: [Capture list] (parameter list), return type {function body}; parameter list and return type can be omitted at some time; cannot have default parameters
  14. Capture list: Just capture local non-static variables, divided into value capture and reference capture; The value of the variable captured by the value is a copy of the lambda creation, to change the need to add the mutable keyword after the parameter list; Reference capture to ensure that the variable still exists when the lambda executes, whether it is mutable by a constant reference
  15. Implicit capture: Let the compiler infer which variables to use based on the code in the lambda body, use & or = parameters to represent reference captures or value captures, and mix implicit and explicit captures in a different way
  16. Lambda returns: The lambda Body contains only one return statement to omit the return type, otherwise the lambda defaults to return void, and the return type must be specified
  17. Bind function: Auto newcallable = bind (callable, arg_list); The parameters passed to Newcallable are passed to arg_list in the order of the placeholder parameters in callable
  18. Placeholder: Shaped like _n,n is an integer; defined in std::p laceholders namespace
  19. Binding reference Parameters: Parameters of bind that are not placeholders are copied to the callable object by default, and you want to pass it to bind an object without copying it, you must define it in the header file functianal using ref or Cref;bind, placeholders, ref.
  20. Insert iterators: Back_inserter, Inserter, Front_inserter call container operations push_back, INSERT, Push_front;*it, ++it, it++ return it
  21. Stream iterator: treats the corresponding stream as a sequence of elements of a particular type; Istream_iterator input, ostream_iterator output
  22. Istream_iterator: An empty istream_iterator can be used as a trailing iterator; compare two istream_iterator if equality must read the same type, if both are trailing iterators or bound to the same input is equal
  23. Ostream_iterator:It, ++it, it++ all return to it; It is recommended to be consistent with the use of other iterators and easier to modify in the future
  24. Reverse iterator: rbegin points to the tail element, rend to the first element, the increment operation to the previous element, and the base operation of the reverse iterator to the normal iterator, but the forward and backward iterators point to different elements when they convert to each other.
  25. The iterator required by the algorithm: input iterator, output iterator, forward iterator, bidirectional iterator, random access iterator, C + + standard indicates the minimum class for each iterator parameter of the algorithm, but the compiler usually does not report the error
  26. Algorithm naming: An algorithm that accepts predicates to override default operators, or that does not accept additional parameters, is usually overloaded, and an algorithm that accepts predicates to replace element values has additional _if, such as find_if, and additional _copy, such as Replace_copy, that are copied to the extra space, and some algorithms provide Copy and _if, such as remove_copy_if
  27. Linked list algorithm: List and forward_list have their own function members sort, merge, remove, reverse, unique, can change the underlying container, prefer to use them instead of the general algorithm
  28. Splice Member: A list-specific algorithm that moves one section of a linked list to a specified position in another list, to ensure that the destination of the move is not within the range to be moved
Associative containers
  1. Associative container classification: set or map, whether the keyword is duplicated, whether the keyword is ordered or not
  2. Associative containers: List initialization, no support for location-related operations, no support for parameters for element values and corresponding number of constructs or inserts; Iterators are bidirectional
  3. Ordered containers: The keyword type must define a comparison method, using the < operator by default, to customize a strict weak-order
  4. Strict weak order: not at the same time "less than equals" the other side; "Less than equals" has transitivity; both sides are not "less than equals" the other party is called "equivalence", "equivalence" has transitivity
  5. Pair type: An initializer surrounded by curly braces to return objects of type pair, older versions only allow explicit construction
  6. Associative container iterator: Map Value_type is Pair<const key_type, mapped_type> So the map iterator can only change the value of the keyword map, cannot modify the keyword; set value_type equals Key_ Type, which is a const keyword and cannot be modified
  7. Associative container insert: inserted only if the keyword does not exist, the function returns a pair that contains an iterator to the element, and a bool type that indicates whether the insert succeeded
  8. Associative container erase: If an iterator is passed in, it must be guaranteed to point to the real element, and if the keyword is passed in, returns the number of all elements of that keyword that were deleted.
  9. Map subscript Operation: Map subscript operation returns Mapped_type, dereference return value_type; If the keyword does not already exist, it will create a new element that has a corresponding keyword with a value of 0, which already exists to return the most recently assigned value; only for maps and UNORDERS_MAP
  10. Find elements: Find (first equals iterator), count (number), Lower_bound (first iterator with less than equals), Upper_bound (first greater than iterator), Equal_range (returns an iterator pair, Represents all equal heads and trailing positions)
  11. Unordered associative containers: Using the keyword's hash function and the = = operator, you cannot directly define an unordered container with a keyword type of custom class type, you must provide your own hash template version, or in another way, a default comparison operation similar to an ordered container overload keyword type
  12. Manage buckets: Unordered containers are organized as a set of buckets on storage, each bucket holds several elements of the same hash value; the performance of unordered containers depends on the quality of the hash function and the number and size of the buckets; functions for managing buckets include bucket interfaces, bucket iterations, hash policies
Dynamic memory
  1. Dynamic Memory: In addition to static memory and stack memory, each program has free space (heap) for storing dynamically allocated objects, objects allocated in free space are not destroyed until explicit release or program end
  2. Smart pointer: Automatically releases the objects that are pointed to and the memory occupied by the object; shared_ptr can point to an object, Unique_ptr exclusive to the object; Smart pointers do not support pointer arithmetic operations
  3. Reference count: shared_ptr associated counter, increment at copy shared_ptr, decrement at assignment or destroy, 0 automatically release Management object
  4. Scenarios using dynamic Memory: No knowledge of the number of objects, exact types of objects, shared data between multiple objects
  5. Direct Memory management: New allocates memory, delete release, cannot depend on the default definition of class object copy, assignment, destroy; built-in type is default initialized to undefined, it is recommended to initialize directly with parentheses, and auto can only be used if there is only a single initializer in parentheses
  6. The dynamically allocated const:new assigns the const object to be legal, its value cannot be changed, but itself can be destroyed by the delete
  7. Null-dangling pointer: A pointer to a piece of memory that once saved the data object but is now invalid, and the delete pointer becomes a null-dangling pointer, which is suggested to be assigned a value with nullptr
  8. Initialize the smart pointer: cannot do the built-in pointer to the smart pointer implicit conversion, must use the direct initialization form; The smart pointer uses the delete release by default, so the normal pointer used to initialize the smart pointer must point to dynamic memory, and the managed resource is not the new allocated memory. You must pass in a filter instead of the delete
  9. Mix smart pointers and normal pointers: shared_ptr binds a normal pointer and should not use a built-in pointer to access the memory; You can use get to pass access to code when you are sure that the code does not delete the pointer, do not use get to initialize or assign a value to another smart pointer
  10. Modify the Shared_ptr Shared object: Call unique when changing the underlying object to determine if it is a user only, and if not, make a new copy with reset
  11. Unique_ptr: Normal Copy or assignment is not supported, but can be copied or assigned to a unique_ptr that is about to be destroyed, such as a function return value; Call release or reset transfers the ownership of the pointer from one non-const unique_ptr to another Unique_ PTR, call reset () or assign a value with nullptr to release the object, release will only sever the management relationship
  12. Unique_ptr: Unlike share_ptr, the removal device affects the type and construction process, and the overload-removing device must indicate the type of the delete in the angle brackets and specify a callable object (the delete) in the parameter list
  13. WEAK_PTR: is a weak reference to a shared_ptr object, but does not change the reference count; Call lock returns a pointer to the SHARED_PTR object when the object counter is 0 o'clock returns null shared_ptr
  14. Assign a dynamic array: Use new t[] to allocate a specified amount of memory, return an element type pointer instead of an array, use empty brackets or curly braces to initialize arrays, but you cannot have an initializer in parentheses, so you cannot use auto; You can allocate an array of 0 lengths, and the returned pointer resembles a trailing pointer
  15. Releasing the dynamic array: delete [] release, empty square brackets are required, otherwise there will be no warning but the behavior is abnormal
  16. Smart pointers to Dynamic arrays: Unique_ptr manages the array of new allocations, followed by an empty parenthesis after the object type in the angle brackets, and cannot use the dot or arrow operators to access the elements in the array using the subscript operator; shared_ptr cannot manage dynamic arrays directly, you must provide your own delete , and you can access the array element only by using the pointer arithmetic operation with the get built-in pointer
  17. Allocator class: Allocate allocates the original, non-constructed memory of a certain size, and the deallocate parameter must be the pointer returned by allocate and the size of the allocate passed in, and Deallocate is called before destroy destructors each object created. Allocate call Cnostruct construct object, or call Uninitialized_copy[_n] Copy object, or Uninitialized_fill[_n] to populate uninitialized memory

Reprint please indicate the source

"C + + Primer" Part II: C + + standard library

Related Article

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.