C + + Primer Fourth Edition reading notes (ii) standard library type

Source: Internet
Author: User
Tags bitset uppercase letter

C + + defines a content-rich standard library of abstract data types, of which the most important standard library types are string and vector, which define variable-size strings and collections, respectively. strings and vectors tend to use iterators as a companion type for accessing characters in a string, or elements in a vector.

Another standard library type is Bitset, which provides an abstract way to manipulate the set of bits.

String types support variable-length strings, which are used by vectors to hold a set of objects of a specified type.

The Bitset class standard library type provides a more convenient and reasonably effective language-level abstraction facility. This class allows you to treat a value as a set of bits.

1.1 Using Declarations for namespaces

Using means that the name of the right-hand operand can be found in the scope of the operand. For example, the name CIN in Std::cin is defined in the namespace Std.

The using declaration is one of the safest mechanisms

1. A using declaration is required for each name

A using declaration can only act on one namespace member at a time. A using declaration can be used to explicitly specify the name in the namespace used in the program, and if you want to use several names in STD (or other namespaces), you must provide a using declaration for each name that you want to use.

2. Class definitions using standard library types

In one case, you must always use the fully qualified standard library name: in the header file. The reason is that the contents of the header file are copied to the program by the preprocessor.

2.1 Standard library String type

2.1.1 definition and initialization of string objects

When an object initializer is not explicitly specified, the system uses the default constructor.

Several ways to initialize a string object
string S1; Default constructor, S1 is empty string
String S2 (S1); Initialize S2 to a copy of S1
String S3 ("value"); Initializes S3 to a copy of a string literal
String S4 (N, ' C '); Initializes S4 to n copies of the string ' C '





2.1.2 the read and write of a string object

Input operator of type string:

(1), read and Ignore all whitespace characters (such as spaces, line breaks, tabs) at the beginning.

(2), read the character until the white space character is encountered again, read terminates.

such as: if the input to the program is "Hello world! (note the opening and closing spaces and tabs), the screen will output "Hello" with no spaces.

1. Read into the unknown destination string object

2. Read the entire line of text with Getline

This function accepts two parameters: an input stream object and a string object. The Getline function reads from the next line of the input stream and saves the contents of the read to a string, but does not include a line break. Unlike the input operator, Getline does not ignore the beginning of the line break. As long as the getline encounters a newline character, even if it is the first characters entered, Getline will stop reading and returning. If the first character is a line break, the string argument is set to an empty string.

2.1.3 operation of a String object

Common String Operations
S.empty () Returns true if S is an empty string, otherwise false
S.size () Returns the number of characters in S
S[n] Returns the character of position N in S, where the position is counted starting from 0
S1 + s2 Concatenate S1 and S2 into a new string, returning the newly generated string
S1 = s2 Replace the contents of S1 with a copy of S2
V1 = = V2 Compares the contents of V1 and V2, returns True if equal, otherwise returns false
! =, <, <=, >= Keep these operators in the habit of meaning
(1), size of string and empty operation

(2), String::size_type type

Logically, the size () member function seems to return an integer value, but in fact, the size operation returns a String::size_type type.

The string class type and many other library types define some matching types. With these companion types, the use of the library type can be machine-independent. Size_type is one of these matching types. It is defined as having the same meaning as unsigned (unsigned or unsigned long) and is sufficiently large to be able to arbitrarily store the length of any string object.

(3), string relational operator

The string class defines several relational operators to compare the size of two string values. These operators actually compare the characters of each string object.

The relational operator compares two string objects with the same policy as the (case-sensitive) dictionary:

1), if the length of the two string object is different, and the short string object matches the previous part of the long string object, the short string object is smaller than the long string object.

2), if the two string object characters are different, the first unmatched character is compared.

(4), assignment of a string object

Implementations of operations such as the assignment of most string library types are subject to some efficiency problems, but it is worth noting that, conceptually, assignment operations do need to do some work. It must first release the associated memory occupied by ST1, and then allocate it to st1 enough to hold the ST2 copy of the memory space, and finally copy all the characters in the ST2 to the newly allocated memory space.

(5) Addition of two string objects

The addition of a string object is defined as a connection. In other words, two or more string objects can be connected by using the plus operator + or the compound copy operator + =.

(6), and string literals of the connection

When a mixed join operation is performed on string objects and string literals, at least one of the left and right operands of the + operator must be of type string.

(7), getting characters from a string object

The string type accesses a single character in a string object by using the subscript operator ([]). The subscript operator needs to take a value of type Size_type to indicate where the character is to be accessed. The value in this subscript is often referred to as "subscript" or "index"

The subscript of a string object starts at 0.

(8), subscript operation can be used for the left value

The standard library does not require an index value to be checked, and the subscript of the index used is undefined, which often results in a critical run error.

2.1.4 Handling of String object characters

We often work with individual characters in a string object, for example: you usually need to know whether a particular character is a blank character, a letter, a number, and so on. The following table lists the various character manipulation functions that apply to the character (or any other char value) of a string object. These functions are defined in the Cctype header file.

functions defined by Cctype
Isalnum (c) True if C is a letter or a number
Isalpha (c) True if C is a letter
Iscntrl (c) True if C is a control character
IsDigit (c) True if C is a number
Islower (c) True if C is a lowercase letter
Isprint (c) True if C is a lowercase letter that can be printed
Ispunct (c) True if C is a punctuation mark
Isspace (c) True if C is a blank symbol
Isupper (c) True if C is an uppercase letter
Isxdigit (c) True if C is a hexadecimal number
ToLower (c) If c is an uppercase letter, it returns its lowercase letters, otherwise it directly returns C
ToUpper (c) If c is a lowercase letter, its uppercase form is returned, otherwise it will return directly to C
Isgraph (c) True if C is not a space but can be printed













3.1 Standard library vector type

Vectors are a collection of objects of the same type, each with a corresponding integer index value. As with string objects, the standard library is responsible for managing the memory associated with the storage element. We call the vector a container because it can contain other objects. All objects in a container must be of the same type.

Before using vectors, you need to include the appropriate header files.

#include <vector>

Using Std::vector

Vector is a template class. A template can be used to write a type one or function definition, and to use multiple different data types.

Declaring a type of object produced from a class template requires additional information, depending on the templates. Vector, for example, must describe what type of object the vector holds, specifying the type by placing the type in angle brackets after the template name:

Vector <int > Ivec;

Vector <Sales_item> Sales_vec;

Vector is not a data type, but just a class template that can be used to define any number of data types. Each of the vector types specifies the type of the element it holds.

3.1.1 The definition and initialization of vector objects

Several ways to initialize vector objects
Vector <T> v1; The vector holds an object of type T. Default constructor v1 is empty
Vector <T> v2 (v1); V2 is a copy of v1.
Vector <T> v3 (n, i); V3 contains n elements with a value of I
Vector <T> v4 (n); V4 n copies of elements containing value initialization

(1), create a number of elements

To create a non-empty vector object, you must give the value of the initialization element. When a vector object is copied to another vector object, each element in the newly copied vector is initialized to a copy of the corresponding element in the original vector. However, these two vector objects must be of the same element type:

Vector <int> IVEC1;

Vector <int> ivec2 (IVEC1);//copy ivec1 to icec2 correct

Vector <string> Svec (IVEC1);//error, type different

The vector object can be initialized with the number of elements and the element value. The constructor uses the number of elements to determine the number of elements the vector object holds, and the element value specifies the initial value of each element:

Vector <int> IVEC4 (10,-1);

Vector <string> Svec ("hi!");

Key concepts: The important attribute of vector objects (and other standard library container objects) is the ability to add elements efficiently at run time. Because vectors increase in efficiency, it is better to add elements dynamically when the element value is known.

(2), initialization of values

If the initialization of the element is not specified, then the standard library will provide an initial value of the element to initialize the value. The initial value generated by the library will be used to initialize each element in the container, depending on the data type of the element stored in the vector.

3.1.2 Manipulation of Vector objects

The Vector Standard library provides many operations similar to string objects:

Vector operation
V.empty () Returns true if V is null, otherwise false
V.size () Returns the number of elements in V
V.push_back (t) Add an element with a value of t at the end of V
V[n] Returns an element of position N in V
V1 = V2 Replace elements in V1 with copies of elements in V2
V1 ==V2 Returns true if V1 is equal to V2
! =, <, <=, >= Keep these operators in the habit of meaning

(1), the size of the vector object

The empty and size operations are similar to related operations of type String.

When you use the Size_type type, you must indicate where the type is defined. The vector type always includes the element type of the vector:

Vector <int>:: size_type;//correct

Vector:: size_type;//error
(2), adding elements to vectors

(3), Vector subscript operation

Objects in the vector are not named and can be accessed by the position of the objects in the vector. You typically use the subscript operator to get an element.

(4), cannot add element with subscript operation

Note: It must be an existing element to be indexed with the subscript operator. Any element is not added when assigned by the subscript operator.

4.1 Introduction to Iterators

In addition to using subscripts to access the elements of a vector object, the standard library provides another way to access elements: using iterators. An iterator is a data type that examines the elements inside a container and traverses the elements.

The standard library defines an iterator type for each standard container. Iterator types provide a more generalized approach than subscript operators: All standard library containers define the appropriate iterator types, and only a handful of containers support subscript operations. Because iterators are applicable to all containers, modern C + + programs tend to use iterators rather than subscript operations to access elements, even for vector types that support subscript operations.

(1), iterator type of container

Each container type defines its own iterator type, such as vector:

Vector <int>:: iterator iter;

This statement defines a variable named ITER whose data type is the iterator type defined by vector <int>. Each standard library container type defines a member named Iterator, and the philosophical iterator is the same as the meaning of the actual iterator type.

Terminology: iterators and iterator types

The first time a programmer encounters a term about an iterator may be confusing, one reason being that the same term iterator often represents two different things. In general, it refers to the concept of iterators, and in particular refers to specific iterator types defined by the container, such as Vector <int>.

It is important to understand that there are many types that are used as iterators, and these types are conceptually relevant. If a type supports a set of deterministic actions that can be used to traverse elements within a container and access the values of those elements, we call this type an iterator.

(2) Begin and end operations

Each container defines a pair of functions named Begin and end, which are used to return iterators. If there are elements in the container, the first element pointed to by the iterator returned by begin:

Vector <int>:: Iterator iter = Ivec.begin ();

The above statement initializes ITER to the value returned by the vector operation named begin.

The iterator returned by the end operation only wants the "next of the end element" of the vector. is often referred to as an out-of-end iterator, indicating that it points to a non-existent element.

Note: The iterator returned by the end operation does not point to any actual element in the vector, but instead it acts as a sentinel, indicating that we have processed all the elements in the vector.

(3), Vector iterator self-increment and dereference operation

The iterator type defines actions to get the element that the iterator points to, and allows the programmer to move the iterator from one element to another. An iterator type can use the dereference operator (* operator) to access the element that the iterator points to:

*iter = 0;

The dereference operator returns the element to which the iterator is currently pointing.

Logically, the self-increment of an iterator is similar to the self-increment operation of an int object. For an int object, the result of the operation is to "add 1" to the int value, while the iterator object is to "move forward one position" in the container. Therefore, if ITER points to the first element, then ++iter points to the second element.

Note: Because the iterator returned by the end operation does not point to any element, it cannot be dereferenced or self-increment.

(4), other operations of the iterator

Another pair of executable iterators is the comparison: with = = or! = operator to compare two iterators, if the two iterator objects point to the same element, they are equal, otherwise they are not equal.

5.1 Standard library Bitset type

Some programs handle an ordered set of bits, each of which may contain a value of 0 (off) or 1 (on). A bit is a concise way to hold yes/no information (sometimes called a flag) for a set of items or conditions. The Bitset class provided by the standard library simplifies the processing of bit sets. To use the Bitset class, you must include the associated header file.

#include <bitset>

Using Std::bitset;

(1), Bitset object definition and initialization

Methods for initializing Bitset objects
Bitset <n> B; B has n bits, each of which is 0
Bitset <n> B (U); B is a copy of the unsigned long type U
Bitset <n> B (s); B is a copy of the string object s that contains a bit string
Bitset <n> B (S, POS, n); B is a copy of n bits starting from position POS in s

Similar to the Vector,bitset class is a class template, and unlike a vector, a Bitset type object differs only in its length and not its type. When defining bitset, it is necessary to specify how many bits the Bitset contains, and the length must be given in parentheses:

Bitset <32> Bitvec;



C + + Primer Fourth Edition reading notes (ii) standard library type

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.