String
1. char_traits character feature class
1) significance: Wrap the universal behavior interface of a specific string element so that the container can execute a specific behavior based on the feature information.
2) A general type name is defined.
Typedef _ ELEM char_type;
Typedef int int_type;
Typedef streampos pos_type;
Typedef streamoff off_type;
Typedef mbstate_t state_type;
Int_type indicates the integer representation when the character element is converted to a specific encoding. pos_type and off_type are used as the types of string index and string element offset respectively, similar to the pointer, iteration type, and pointer in container stack, the offset type of the iterator. The last state_type is used to store the stream status, such as error and format control.
3) defines the character/string operation packaging interface for calling common algorithms
Assign (a, B) defines the process of assigning character B to character a to implement the behavior of a. Operator =
Eq (a, B) defines the equal relationship between A and B, and implements a. Operator =.
LT (a, B) defines the relationship between A and B to implement the behavior of a. Operator <
Compare (a_ptr, B _ptr, CNT) defines the comparison between two strings and returns the int type to implement behavior similar to memcmp.
Length (PTR) defines the length of a string to implement behavior similar to strlen.
Copy (a_ptr, B _ptr, CNT) defines the replication of two groups of strings to implement behavior similar to memcpy
Move (a_ptr, B _ptr, CNT) defines the non-overlapping copying of the two strings to implement behavior similar to memmove.
Assign (PTR, CNT, CH) defines the process of filling strings to implement behaviors similar to memset.
To_int_type (CH) defines the conversion process from char_type to int_type integer.
To_char_type (n) defines the conversion process from int_type to char_type struct type.
Eq_int_type (a, B) defines two int_type equal relationships with the current char_type
EOF () defines the string Terminator, expressed in integer
Not_eof (n) defines non-string Terminator. If the input Terminator is used, 1 is returned. Other inputs return the original value, that is, no EOF () is returned ()
4) int_type should be the integer encoding of the current character type
2. STD: string is not a sequence container. The front () and back () interfaces are not used to retrieve elements at the front and end. STD: String :: OPERATOR [] and pass the streampos type to get a specific element, such as STD: String: size ()-1 as the index to get the last character
Iii. Initialization supported by basic_string
1) default Initialization
2) distributor
3) replication Structure
4) Local replication [_ roff, _ roff + _ count)
5) Local replication + distributor
6) C string [_ PTR, <null>)
7) C string + _ count [_ PTR, _ PTR + _ count)
8) C string + distributor
9) C string + _ count + distributor [_ PTR, _ PTR + _ count)
10) _ count * _ CH
11) _ count * _ CH + distributor
12) iterator [_ ITF, _ ITL)
13) iterator + distributor
Character to string cannot be initialized, but operator = assignment and operator + = accumulate assignment are supported.
Iv. String interval Validity
When the access to the index of a string exceeds the valid range of the string, it will not cause exceptions because the implementation of the string executes subscript access to the built-in character buffer, however, unpredictable results are usually unavailable.
When another string is input as the right value, the size of the string is calculated when the count of the string is greater than the string size.
The actual type of STD: basic_string: size_type is size_t. in Visual C ++ 7.1, it is implemented as unsigned, and STD: basic_string: NPOs is statically set
(Basic_string <_ ELEM, _ traits, _ alloc >:: size_type) (-1 );
When searching for sub-strings and other operations, the function returns the NPOs value to indicate that the index is invalid.
5. compare strings
Allowed comparison objects
1) compare (S2) other strings of the same type
2) compare (p) C-style string
3) compare (Off, CNT, S2) [Off, off + CNT) is compared with S2.
4) compare (Off, CNT, S2, off2, cnt2) [Off, off + CNT) compare with S2 [off2, cnt2)
5) compare (Off, CNT, p) [Off, off + CNT) compare with [p, <null>)
6) compare (Off, CNT, P, cnt2) [Off, off + CNT) are compared with [p, p + cnt2 ).
Returns-1, 0, and 1 as the comparison result of less than, equal to, and greater.
6. Additional data
1) Use operator ++ = to accept other strings, C-style strings and characters
2) use push_back () to append characters and allow back_iterator constructed by string to access
3) append () appending
1. append (s) append string
2. append (S, off, CNT) append string s [Off, off + CNT)
3. append (p) append string [p, <null>)
4. append (p, CNT) append string [p, p + CNT)
5. append (N, C) is filled with N * C
6. append (INF, INL) the input stream [INF, INL)
4) insert () insert
1. insert (Off, S2) inserts a string
2. insert (Off, S2, off2, cnt2) to insert the string s [off2, off2 + cnt2)
3. insert (Off, p) inserts a string [p, <null>)
4. insert (Off, P, CNT) inserts a string [p, p + CNT)
5. Insert (Off, N, C) insert N * C
6. insert (ITER) element default value Filling
7. insert (ITER, c) insert specific elements
8. insert (ITER, N, C) insert N * C
9. insert (ITER, INF, INL) insert [INF, INL)
5) operator + (A, B)
Support operator + in string join Operator Overloading
1. S + S
2. S + P
3. S + c
4. P + S
5. c + S
VII. Search, replace, and clear
1) Find () Search
1. Find (C, off) Find C in S [Off, NPOs)
2. Find (p, off, n) in S [Off, NPOs) to find [p, p + n)
3. Find (p, off) in S [Off, NPOs) to find [p, <null>)
4. Find (S2, off) Search for S2 in S [Off, NPOs)
2) Find () variants
1. rfind () has the input form of find (), Reverse Lookup
2. find_first_of () has the input form of find (), and returns the first matched index.
3. find_last_of () has the input form of find (), and returns the last matched index.
4. find_first_not_of () has the input form of find (). The first unmatched index is returned.
5. find_last_not_of () has the input form of find (), and returns the first unmatched index to the last.
3) Replace ()
1. Replace (Off, CNT, S2) replace s [Off, off + CNT) WITH S2
2. Replace (Off, CNT, S2, off2, cnt2) replace s [Off, off + CNT) WITH S2 [off2, off2 + cnt2)
3. Replace (Off, CNT, p) replace s [Off, off + CNT) with [p, <null>)
4. Replace (Off, CNT, P, cnt2) s [Off, off + CNT) with [p, p + cnt2)
5. Replace (Off, CNT, N, C) replace s [Off, off + CNT) with C * n
When the iterator is used:
6. Replace (INF, INL, S2) to replace [INF, INL) WITH S2
7. Replace (INF, INL, p) Replace [INF, INL) with [p, <null>)
8. Replace (INF, INL, P, CNT) with [INF, INL) [p, p + CNT)
9. Replace (INF, INL, N, C) to replace [INF, INL) with N * C
10. Replace (INF, INL, inf2, inl2) to replace [INF, INL) with [inf2, inl2)
4) Delete erase ()
1. Erase (Off, CNT) deletes s [Off, off + CNT) from string S)
2. Erase (ITER) removes * ITER from string s
3. Erase (ITF, ITL) removes [ITF, ITL) from string S)
8. Retrieve strings
1) Obtain a C-style string
C_str () returns the C-style string pointer of the constant type. Copy (PTR, CNT, off = 0) copies the string of the specified size to the specified pointer. Data () in Visual C ++ 7.1, only c_str () is called.
2) obtain the substring
Substr (Off, CNT) gets a copy of S [Off, off + CNT.
3) copy the substring
Copy (p, off, CNT) to copy s [Off, off + CNT) to P.
9. String Buffer Management
The string has a buffer management interface similar to STD: vector.
Size () to get the valid element length
Max_size () obtains the valid space allocated by the current memory distributor.
Reserve () reserves space for the Buffer Zone
Capacity () gets the buffer capacity
Resize () resets the length of the string and you can specify the initialization value for it.
10. Define the end of the input iterator
The input stream object is passed to istream_iterator to create an input iterator. The input iterator holds the pointer of the input stream object. By default, the pointer is set to 0 when the stream creation and reading fail. In addition, when operator = equals operation is implemented between input iterators, the stream object pointer held is equal and compared. In this way, the input iterator created by default is used to match the end of the input stream.
* When the input stream fails to be read and the user executes the IF and while conditions, the judgment value is converted to the void * type first, or according to operator! Returns the operator void * and operator! Operator, which can define the behavior of the input stream in a Boolean expression, so that when the stream reading fails, the input iterator can be confirmed by a Boolean expression, rather than explicitly accessing the fail () member function:
Void _ getval ()
{// Get a _ ty value if possible
If (_ myistr! = 0 &&! (* _ Myistr> _ myval ))
_ Myistr = 0;
}
STD: basic_istream: Operator> in the preceding formula, STD: basic_istream & type is returned. This type has the following Operator Overloading:
Operator void * () const
{// Test if any stream operation has failed
Return (fail ()? 0: (void *) This );
}
Bool Operator! () Const
{// Test if no stream operation has failed
Return (fail ());
}
11. C-style string
1) string operations
Strcpy (p, P1) copies the string
Strncpy (p, P1, n) copies the specified length string
Strcat (p, P1) Additional string
Strncat (p, P1, n) attaches a specified length string
Strlen (p) returns the string length.
Strcmp (p, P1) Comparison string
Strncmp (p, P1, n) compares the specified length string
Strchr (p, c) searches for the specified character in the string
Strrchr (p, c) reverse lookup in the string
Strstr (p, P1)
Strpbrk (p, P1) takes all the characters of the target string as a set, and searches for any element of the Set in the current string.
Strspns (p, P1) Take all the characters of the target string as the set, and find the offset of any element that does not belong to the set in the current string.
Strcspn (p, P1) uses all characters of the target string as a set, and searches for the offset of any element in the set in the current string.
* The string handler with the specified length fills in the zero-ending character after the processed string
2) string to numeric type conversion
Strtodd (p, ppend) converts double type values from string P, and stores subsequent string pointers to the char * type stored by ppend.
Strtol (p, ppend, base) converts long integer values from string P. base explicitly sets the converted integer hexadecimal value to 0 and determines the hexadecimal value based on the specific format, 0x and 0x prefixes are interpreted as hexadecimal integers, and 0 prefixes are interpreted as octal integers.
Atoi (p) string to int integer
Atof (p) string to double point
Convert an atol (p) string to a long integer
3) when the text is converted to the long type, the errno global variable of C Runtime is set when the value exceeds the indicated range. errno = erange, and strerror (errno) is used to obtain the string corresponding to the error.
4) character check
Isalpha () check whether it is a letter character
Isupper () check whether it is an uppercase letter
Islower () check whether it is a lowercase letter
Isdigit () check whether it is a number
Isxdigit () check whether it is a valid character expressed by a hexadecimal number
Isspace () check whether it is a space character
Iscntrl () check whether it is a control character
Ispunct () Check for punctuation
Isalnum () Check for letters and numbers
Isprint () Check for printable characters
Isgraph () checks whether it is a graphical character, which is equivalent to isalnum () | ispunct ()
Input and Output streams
I. output stream
Ii. operator Output for various stream types
The output stream not only accepts the data type that can be displayed, but also accepts the operator that affects the behavior of the output stream and returns the reference of the output stream, so that operator <concatenates a group of operations.
The following lists some specific output types, their usage and implementation overview.
1) directly call put () for the output of a single character without using operator <
2) Reload operator for the operator <
STD: Hex is one of the control operators of the output stream. It is implemented as a function that accepts the reference of the basic stream type and changes its status to the output hexadecimal format:
Inline ios_base & _ cdecl hex (ios_base & _ iosbase)
{// Set basefield to hex
_ Iosbase. SETF (ios_base: Hex, ios_base: basefield );
Return (_ iosbase );
}
An overloaded version of the output stream will access this operator on behalf:
_ MYT & operator <(ios_base & (_ cdecl * _ PFn) (ios_base &))
{// Call ios_base Manipulator
(* _ PFn) (* (ios_base *) This );
Return (* This );
}
Finally, the reference of the current output stream object is returned, and it is connected to another operator in a string <operation. The following access form can be obtained through the application of the operator:
STD: cout <STD: SETW (10) <STD: Internal <STD: Hex <STD: uppercase <STD :: showbase <STD: setfill ('0') <int (768*1024) <STD: Endl;
3) STD: boolalpha operator indicates that the output stream uses the symbolic form to indicate true or false
4) for the pointer type, the output hexadecimal format is used to indicate the address format, even if STD :: showbase is used to indicate the prefix of the output stream and other operators that attempt to affect the output format of pointer data. The address format of the pointer will not change.
Int * P = STD: auto_ptr <int> (New INT). Get ();
STD: cout <p <STD: Endl;
3. input stream Segmentation
Operator> split the input stream by the blank type, that is, the character types corresponding to isspace (): blank, vertical table, horizontal table, return, newline, Newpage, and so on. Of course, for input types that have format requirements, the system suspends the unmatched input type.
1) STD: CIN> intval;
If the int type is used to read unexpected data, set ios_base: failbit to the stream status. STD: cin. rdstate () & STD: ios_base: failbit to get this status.
2) STD: cin. Width (N );
Explicitly indicates the length of data read by the string to prevent overflow of the target storage, including the automatically added '/0' for the target storage. If it is passed to STD :: string and other standard library string types do not contain the '/0' null character at the end, and the transfer to other types is not limited by this width, and only affects the next input operation.
Iv. Stream status
1) significance: the caller can access the status to understand the operation results and exceptions of the stream.
Good () test goodbit
EOF () test eofbit
Fail () test badbit | failbit
Bad () test badbit
Rdstate () gets the stream status
Clear ([flag]) Clear/set stream status
Setstate (FLAG) additional stream status
2) The next read will fail due to an abnormal stream.
5. Test the Boolean value of the stream object
Bool Operator! () Negative.
Operator void * () is used for conditional judgment. The Compiler forces the transformation to void *. In this case, 0 is returned to indicate false.
6. Non-formatted input
Int_type get () extracts int_type data from the input stream, corresponding to a specific type of encoding characters
Get (c) extracts character data
Get (p, n) gets a string of N length to P, split by linefeed
Get (p, N, delim) extracts the string of N length to P, specifying the delimiter
Ignore (n, delim) ignores strings of N length and specifies the delimiter
Read (p, n) reads n characters
Gcount () gets the length of the extracted characters for the last unformatted Input
Get (p, N, delim) does not retrieve the delim itself, which is different from Getline. You must manually attach it to the target string as needed. In addition, the continuous occurrence of delimiters will lead to the removal of an empty string, ios_base: failbit is appended to the stream status, which will cause the failure to judge the get () condition.
VII. Stream exceptions
Ios_base: Exceptions () to obtain the exception mask
Ios_base: Exceptions (iostate) sets the exception mask.
Ios_base: exception class of the failure stream
The status bit appended with the exception mask throws an ios_base: Failure exception when the stream encounters a specific State.
VIII. Stream connection
Basic_ios: Tie () retrieves the output stream pointer associated with the input stream
Basic_ios: Tie (basic_ostream &) sets the output stream pointer to be connected to the input stream
* The output stream associated with the input stream always refreshes the output stream status before the input of the input stream request, and uses basic_ostream: flush () to immediately write data to the disk file in the file stream.
9. Sentry
1) significance: Sentry is a set of automatic objects of input and output stream objects. It uses constructor and destructor to perform preprocessing and post-processing in stream operations. For example, attaches a thread lock to the stream buffer.
2) When the sentry object type executes condition judgment, it is implicitly converted to the bool type, and the pointer type is converted to the void * type. Overload sentry: Operator bool () to return the available status of the stream from sentry, so as to guide the actual action of the stream. If a thread conflict may cause stream unavailability, sentry must provide such information.
Output stream format
I. ios_base format settings
Flags () read flag
Flags (FMT)
SETF (FMT) Additional flag
SETF (FMT, mask) adds a flag Based on the mask
Unsetf (mask) indicates the position of the mask.
* There is an important difference between SETF (FMT) and SETF (FMT, mask). For all bits located below the same mask value, when a mask is input, it is cleared in advance. This ensures that the flag settings below the mask value are mutually exclusive, while SETF (FMT) the option of multiple positions may appear for all bits under the same mask value.
2. Control the operator of the output stream format bit
Most of the operators used to control the output stream format are located below the <IOS> file. They can be appended to the basic_ostream: Operator <() backend and affect the corresponding output stream.
1) alignment format adjustfield
Right alignment on the right side. Default setting
Left-side alignment
Internal alignment of internal
2) Base basefield
Decimal, default setting
Hex hexadecimal
Oct octal
4) floatfield
Scientific scientific notation
Fixed count
3) Output
Showbase/noshowbase Display Base-modified prefix
Showpoint/noshowpoint always prints the decimal places at the end, including 0. By default, noshowpoint
Boolalpha/noboolalpha: Use a string to print a Boolean value. The default value is noboolalpha.
Showpos/noshowpos: Specifies the printing symbol, which includes positive numbers. The default value is noshowpos.
Skipws/noskipws skips spaces. The default value is noskipws.
The uppercase/nouppercase hexadecimal format uses numbers in uppercase. The default value is nouppercase.
5) mask
Ios_base: adjustfield = ios_base: Right | ios_base: Left | ios_base: Internal
Ios_base: basefield = ios_base: Dec | ios_base: Hex | ios_base: Oct
Ios_base: floatfield = ios_base: Scientific | ios_base: fixed
* The flag name and Operator Used in the mask may have the same name, but not the same symbol.
3. Use skipws to ignore blank input streams
Ignore the blank characters in the input stream to help you effectively obtain numeric values and other types to avoid failure.
STD: CIN> STD: noskipws;
STD ::Cin. Exceptions(CIN. failbit );
STD: CIN> intval;
If the preceding example contains a string with spaces at the start, an exception is thrown. The blank character is not a valid value format character.
Iv. Floating Point Output
Ios_base: precision (). The default value is 6.
Ios_base: precision (n) Setting precision
* For the default float output, the precision affects all valid bits, and the fixed precision affects decimal places. For scientific notation scientific, the precision affects the decimal places.
* When the default expression form integer is greater than the precision range, or the first non-zero digit is greater than the decimal point, scientific notation is used.
5. Set the width of the output stream
1) Use the ios_base member function width ()
Width () is used to obtain the output width of the output stream. If it cannot fully represent an integer or a real number with decimal places, it must at least extend to the width reasonably expressed, including the valid precision bit, by default, 0 is returned, indicating that the width is not limited.
Width (n) sets the output width of the output stream, which only affects the next output. For example, we want to output a 32-bit hexadecimal number that contains the "0x" prefix. A total of 10-digit output is required. Use ios_base: width (10) to set the output width, set the padding character to '0' and use basic_ios: Fill ('0 '), for the output stream, the pass operator internal will align the base modifier prefix and value to both sides of the restricted width area by internal alignment, with the '0' character in the middle.
2) use the operator SETW (N)
Similar operators include setprecision (n) that controls the output precision of floating points ).
6. Manipulator
1) operator implementation
The operator <or operator> operator of the overloaded stream, which accepts non-member/static member functions of a specific type and accesses the function on behalf of it, which is called a stream operator. The function is used to access the member functions and data of the stream by referencing the stream. The following is a function that can be used as an operator:
Inline ios_base & _ cdecl right (ios_base & _ iosbase)
{// Set right in adjustfield
_ Iosbase. SETF (ios_base: Right, ios_base: adjustfield );
Return (_ iosbase );
}
2) Parameters
The common operator only accepts the function pointer to forward access rights in operator <. In order for a function that obtains the forwarding access permission to pass a specific parameter, it is not feasible to pass only the function pointer. A type template dedicated to a type of operator must be implemented to hold the function pointer and parameter, a function that accepts a parameter will instantiate an object that carries the function pointer and parameter, and reload the operator <or operator> operator of the object.
An operator with parameters:
_ Smanip <streamsize> _ cdecl SETW (streamsize wide)
{// Manipulator to Set width
Return (_ smanip <streamsize> (& swfun, wide ));
}
Reload the input and output operators of the stream for this operator:
Template <class _ ELEM, class _ traits, class _ Arg> inline
Basic_istream <_ ELEM, _ traits> & _ cdecl operator> (
Basic_istream <_ ELEM, _ traits> & _ istr, const _ smanip <_ Arg> & _ manip)
{// Extract by calling function with input stream and argument
(* _ Manip. _ pfun) (_ istr, _ manip. _ manarg );
Return (_ istr );
}
3) a parameter operator in the standard library
Resetiosflags (f) Clear the flag in the specified format
Setiosflags (f)
Setbase (n): Set the base number of an integer.
Setfill (c)
Setprecision (n) Setting precision
SETW (n) to set the width
File stream and string stream
1. Flow Hierarchy Diagram
1) iostream is a stream with both read and write capabilities. It is completed by accessing the write buffer and read buffer respectively.
2) is_open () check whether the file stream has been opened
3) What is the difference between ios_base: ATE and ios_base: app file stream opening flag?
The ATE is only at the end of the file when the first read is performed.
The app always appends data to the end.
Note _ nocreate to avoid re-creation every time you open the file and require that the specified file has been opened.
2. Use a Global Counter to confirm the current initialization status. Use the counter for the object construction that needs to confirm its creation priority.
3. String stream stringstream
Stringstream does not depend on files and input/output. It uses the appended string as the base point to operate text streams or returns the string type.
Iostream is the base class of stringstream. It provides rich format control, hexadecimal control, floating point control, and other operations. These operations are implemented based on stream technology. Append a string through a string stream, and then return a string after performing a series of operations, which can be more flexible and more secure than the C-style String cache operations for character formatting.
Iv. Buffer Zone
Different streams use different memory or peripherals, and it is helpful for the same class of stream objects to allow changes to the implementation of the buffer. Therefore, the buffer is implemented as an independent streambuf type, which abstracts the actual actions to access the memory and peripherals.
1) The stream buffer encapsulation object implements two sets of pointers pointing to the output stream buffer and the input stream buffer respectively, which can control the output and input respectively.
In the base class of the output stream, ostream uses the member function seekp () to move the position of the character, that is, "Seek put position ".
Seekp (pos_type) locates the output buffer to the specified position
Seekp (off_type, ios_base: seekdir) locates the position of the output buffer based on the offset and direction.
* Ios_base: seekdir three values can be passed:
Static const _ seekdir beg = (_ seekdir) 0;
Static const _ seekdir cur = (_ seekdir) 1;
Static const _ seekdir end = (_ seekdir) 2;
Seekp () internally calls the pubseekpos (_ POs, ios_base: Out) member function of streambuf.
Correspondingly, seekg () acts as a member function of istream, changes the index pointer of the input stream, and calls the pubseekpos (_ POs, ios_base: In) member function of streambuf internally.
2) Each stream object is associated with a specific stream buffer pointer.
3) The stream index pointer location operation is used only when the operation device associated with the stream makes the location meaningful. For example, the output stream may be implemented for every write of data, the data will be immediately refreshed to the standard output without staying in the buffer zone. it is meaningless to operate the stream index pointer on this buffer zone, and the ios_base pointing to the invalid element bit is triggered :: failbit exception
4) input stream operations
Seekg (pos_type)
Seekg (off_type, ios_base: seekdir)
Putback (c) returns the specified character to the current position of the input stream buffer. If the input stream fails, an ios_base: badbit exception is set.
Unget () returns the character that was last read from the input stream. If it fails, an ios_base: badbit exception is set.
Peek () retrieves a character from the input stream and does not remove it from the input stream.
Sync () synchronizes the input device and the input stream buffer
5) basic interaction between iOS and the buffer zone
Rdbuf () Fetch and set the associated buffer
Imbue () Dip buffer localization site
Narrow (C, char_c) uses the current localization to convert the current character encoding to the char type
Widen (char) uses the current localization to convert from the char type to the current character encoding
For the last two items, one of the most common applications is to process line breaks and zero-tail width of the wide character set. For example, to use only the '/0' plaintext string, use widen () member functions, which can easily convert common ASCII characters to the current localized encoding.
5. Buffer Zone Model
1) input stream easing
Dashboard
Egptr () input stream buffer tail end
Gptr () Current element index
Front-end of the eback () input stream buffer
Gbump (n) changes the element index of the buffer.
Setg (beg, cur, end) sets the input stream buffer to point to the storage pointer
2) output stream Buffer Interface
Front-end of the pbase () output stream buffer
Pptr () Current element index
Epptr () output stream buffer tail end
Pbump (n) changes the element index of the buffer.
Setp (beg, end) sets the output stream buffer to point to the storage pointer
6. Synchronization with C-style Io
Ios_base: sync_with_stdio (bool) sets the C and C ++ libraries to synchronize the use of conventional input and output devices, and may cause some performance loss.