C++ Knowledge Summary (2)--Strings and Arrays

Standard library type string

The standard library type string represents a variable-length sequence of characters.

Using a stringtype requires adding the header file first #include<string>, and since it's defined in the namespace std, it's also added using std::string;.

There are several ways to initialize a string :

write picture description here

The initialization using the equal sign performs copy initialization , which copies the initial value on the right side of the equal sign to the newly created object; without using the equal sign, direct initialization is performed .

Most operations on strings are given below :

write picture description here

During read operations, the string object automatically ignores leading whitespace (i.e. spaces, newlines, tabs, etc.) and reads from the first real character until the next whitespace is encountered.

And if you need to read a line, you can use the function getline , whose parameters are an input stream and a string object, read content from the given input stream until a newline character is encountered, note that it will also read the newline character Takes it in, but doesn't save it to the string object.

The size() function returns the length of the stringstring::size_type object. The type of the return value is an unsigned value that can hold the size of any string object.

When combining string objects with character literals and string literals in a statement, you must ensure that at least one of the operands on either side of each addition operator is a string . Also, string literals and strings are different types.

A set of standard library functions are defined in the cctype header file to change the characteristics of a character, as follows:

write picture description here

The form of a range-based forstatement is as follows:

string str("string");
for(auto c : str)
  cout << c << endl;

The above is to use this forstatement to output streach character in the string, and if you want to change the content of the string, you need to define the loop variable as a reference type, as follows:

string str("string");
for(auto &c : str)
  c = toupper(c);
cout << str <<endl;

The above code is to turn strall the strings in uppercase letters, and the key point is auto &cthe use of reference types in .

Standard library type vector

The standard library type vector represents a collection of objects, where all objects are of the same type.

To use vector, you must make the following usingdeclarations and add header files:

#include<vector>
using std::vector;

The C++ language has both class templates and function templates , vectorbut it is a class template.

A template is not a class or function itself, you can think of a template as a description of what a compiler-generated class or function writes. The process that the compiler creates a class or function from a template is called instantiation . When using a template, it is necessary to indicate what type the compiler should instantiate the class or function into.

For class templates, you need to provide some additional information to specify what class the template is instantiated into. The information provided is always this: that is, the template name is followed by a pair of angle brackets, and the information is placed within the brackets. For example, an object of a saved type vector<int> ivec;is defined .intivec

vectorCan hold most types of objects as its elements, but since references are not objects, there is no such thing as containing a reference vector.

The initialization vectormethod is as follows:

write picture description here

In general initialization, parentheses are used, and the provided value is used to construct vector, as in the above example v3,v4; and if curly braces are used, it generally means that we want to use a list to initialize vectorthe object, but if the provided value cannot be List initialization, as vector<string> v{10};this means vthere are 10 default-initialized elements, or as vector<string> v{10, "hi"};this means vthere are 10 elements with the value "hi".

Note that a range statement cannot be used if the loop body contains vectorstatements that add elements to an object for, and the range forstatement body should not change the size of the sequence it traverses.

Introduction to Iterators

The iterator can also implement the function of the subscript operator, that is, it can access stringthe characters vectorof the object or the elements of the object.

The iterator provides indirect access to the object. Unlike the pointer, the iterator is not obtained by using the address character. The type with the iterator also has the member that returns the iterator. These types all have members named begin and end , where the begin member is responsible for returning an iterator pointing to the first element, and the endstring member is responsible for returning an iterator pointing to the "next position of the tail element" of the container or object, that is, its indication It is a non-existent tail-end element of the container, so it is often called a tail-end iterator . If the container is empty, begin and end return the same iterator.

The operators of the iterator are as follows:

write picture description here

In fact, we generally don't know, or need not know, the exact type of the iterator, just as we don't know the exact type of the members of stringand vector. size_typeIn fact, the standard library types that have iterators use iterator and const_iterator to represent the type of iterators, like:

vector<int>::iterator it;   // it能读写vector<int>的元素
string::iterator it2;       // it2能读写string对象中的字符

vector<int>::const_iterator it3; // it3只能读元素,不能写元素
string::const_iterator it4;     // it4只能读字符,不能写字符

A const_iterator is similar to a constant pointer. It can read but not modify the value of the element it refers to. If the vectorOR stringobject is constant, only const_iterator can be used ; on the contrary, the object of the iterator is readable and writable, and only the vectorOR stringobject is not constant, then these two can be used by anyone.

Dereferencing an iterator gives you the object pointed to by the iterator, and if that object's type happens to be a class, you might want to further access its members. For example (*it).empty(), if it itis an vectoriterator of an object, this code is vectorthe emptyfunction called, but note that there must be parentheses here, otherwise the dot operator is a pointer it, not itthe result of dereferencing. You can use the arrow operator -> to achieve the same effect, i.e. it->empty()it is equivalent to (*it).empty().

Note that any loop body that uses an iterator should not add elements to the container to which the iterator belongs.

array

Array is a composite type whose declaration form is the name a[d]of athe array, dbut the dimension of the array. The dimension must be greater than 0 and must be a constant expression, that is, the dimension should be known when compiling.

Like built-in type variables, if an array of a built-in type is defined inside a function, default initialization will make the array contain undefined values.

You cannot copy the contents of an array to another array as an initial value, and you cannot use an array to assign values ​​to other arrays, that is, the following behaviors are wrong:

int a[] = {0,1,2};  // 含有3个整数的数组
int a2[] = a;       // 错误:不允许使用一个数组初始化另一个数组
a2 = a;             // 错误:不能把一个数组直接赋值给另一个数组

In C++, pointers and arrays are closely related, and when using arrays, the compiler generally converts them to pointers.

Usually, the address character is used to obtain a pointer to execute an object. The address character can be used for any object, and the elements of an array are also objects. Therefore, using the address character on an element of an array can get a pointer to the element.

In addition, arrays have a special feature: in many places where the name of an array is used, the compiler will automatically replace it with a pointer to the first element of the array. as string *p2 = nums;equivalent to p2 = &nums[0];. So in most expressions, using an object of type array is actually using a pointer to the first element of the array.

When using an array as autothe initial value of a variable, the inferred type is a pointer rather than an array.

The new C++11 standard introduces two functions named beginand end. These two functions are of the same name as the two member function types in the container, but the array is not a class type, so these two functions are not member functions. The correct use form is Take arrays as their arguments.

Pointers to array elements can perform some iterator operations such as dereferencing, incrementing, comparing, adding to integers, subtracting two pointers, etc.

Among them, the result of the subtraction of two pointers is the distance between them, but the two pointers must point to the elements in the same array ; and for the comparison operation, the two pointers are also required to point to the elements of the same array or the end of the array the next position of the element , otherwise it cannot be compared;

You can use an array to initialize an vectorobject, just specify the address of the first element and the last address of the area to be copied, such as:

int int_arr[] = {0, 1, 2, 3, 4, 5};
// ivec有6个元素,分别是int_arr中对应元素的副本
vector<int> ivec(begin(int_arr), end(int_arr));
// 也可以是数组的一部分,下面是拷贝三个元素:int_arr[1], int_arr[2], int_arr[3]
vector<int> subVec(int_arr+1, int_arr+4);

A multidimensional array is actually an array of arrays.

When dealing with multidimensional arrays using range forstatements, all but the innermost loop's control variable should be a reference type.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325990453&siteId=291194637