string
andvector
The two most important library types are string, which represents a variable-length sequence of characters, and vector, which holds somethingGiven type object
Variable length sequence of.- Iterators are matching types of string and vector. They are often used to access string characters or elements of a vector.
- Built-in arrays are more basic types, of which string and vector are abstractions.
- Built-in types are defined directly by the C++ language and represent the capabilities of most computer hardware itself. The library defines another set of types with more advanced properties.
Namespace using declaration
Field operators ::
The compiler looks for the name on the right from the scope shown by the name on the left of the operator.- With a using declaration, you can use a name without specifying the namespace each time, as in using namespace::name; , so that you can use name directly later.
- Each using introduces a name, so each name must have its own using
- Because the header file code will be
Copy it to the file that references it
, so header code should not use using
Library type String
- String is a library type representing a sequence of variable-length characters, defined in the header string and namespace STD.
Define and initialize a string
Initialization mode:
Direct initialization
: Initializes variables with parentheses instead of equal signs. callThe constructor
Copy initialization
: Initializes a variable with an equal sign. Calls the overloaded assignment operator- We can construct temporary quantities with direct initializers and then copy initializers: string s=string(10,’c’);
string s1; // Default initialization, empty string s2(s1); // initialize directly, s2 is a copy of s1. // copy initialization, s2 is a copy of s1, equivalent to the previous string s3("hiya"); // initialize directly to a literal constant string s3="hiya"; // copy initialization to a literal constant, equivalent to the previous string s4(10,'c'); // Initialize directly to 10 characters 'c'Copy the code
String operations
Read string from iostream
:>>
When read, the string ignores the leading whitespace (including Spaces, newlines, tabs, and so on) and reads from the first real character until the next whitespace.- The string object
<<
and>>
Also the ioStream object to the left of the return operator. - If you want to preserve whitespace when reading from iostream
getline
Function that reads from iostream until a newline (A newline is also read in
), and store what you read into a string object (No newline character is saved
).
getline(cin, inputLine);
Copy the code
- Getline also returns its iostream and can be used as a condition of a while.
- Empty returns a bool based on whether the string is empty
- Size Returns the length of the object (the number of characters).
- The size function returns a string::size_type (obtained by decltype), which is unsigned and can hold the size of any string. (
attention
: can’t mix size with int.) - = = and! = Verify that the contents of two strings are identical, <, <=, >, >= compare the dictionary order of two strings (case sensitive)
- Copy and assign strings with =
- + concatenates two strings. You can concatenate a string and a string literal (conversion), but you cannot concatenate two string literals. Because string and string literals are different types
Handling of characters in a string
- When using the range for, if you want to change the value of an element in a sequence, you must define the loop variable as
Reference types
. - Example: Change elements in the scope for
string s("hello,world!" ); For (auto &c:s) // To change an element in a sequence, you must declare a reference type c=toupper(c); cout<<s<<endl;Copy the code
- There are two ways to access a single character in a string:
Subscripts and iterators
- Subscript operator
[]
Takes a string::size_type (unsigned) and returns the value of the character at that positionreference
(so characters can be modified). An index supplied with a signed value is converted to an unsigned value of string::size_type - Example: Iterate with subscripts
for(decltype(s.size()) index=0; // Use decltype to push string::size_type index! =s.size() && ! isspace(s[index]); // Check the right side only if the left side is true. ++index) {s[index]=toupper(s[index]); }Copy the code
The library type vector
- Vector represents a collection of objects, all of the same type.
- Vector is called because it holds other objects
The container
- The vector is a
Class template
. C++ has class templates and function templates. A template is not a class or function per se; you can think of a template as an illustration of the class or function that the compiler generates. The process by which the compiler creates a class or function from a template is calledinstantiation
- When classes or functions are generated from templates,
Type must be specified
- in
C + + 11 before
Vector, whose element is vector, is required in template variablesThe space
- Example: Declare an object from the template vector
vector<int> ivec; // The element is an int vector<Sales_item> Sales_vec; // The element is an object of type Sales_item. // The element is vector<string>. Vector <vector<string> > file; // before C++11, the elements were vectors <string>Copy the code
Define and initialize a vector
- Parentheses are
structure
And the curly braces areList initialization
. However, when the curly braces cannot be initialized, an attempt is made to replace the curly braces with parentheses.
vector<string> v5{"hi"}; // There is one element, which is the string "hi" vector<string> v6("hi"); Vector <string> v7{10}; vector<string> v7{10}; // The list cannot be initialized to construct. Vector <string> v8{10,"hi"}; // The list cannot be initialized to construct. There are 10 elements, all "hi"Copy the code
Vector operations
- Creating an empty object and then pushing it back is very efficient and faster than setting the size at creation time and then modifying it.
- The size method on a vector returns the number of elements in the vector of type
vector<type>::size_type
Type. To use size_type, you must first specify the type of size_type. - For vector indexes, the subscript types are corresponding
Size_type type
- You cannot add elements with subscripts, and accessing nonexistent elements with subscripts raises an error (
Compile without error
), such as buffer overflow, etc - One way to ensure efficient access to elements is to use scopes
for
The iterator
- String objects do not belong to containers, but are operationally close to them
- Iterators provide arguments for element objects
Indirect access
, similar to a pointer. The object isElements in a container
Or,Characters in string
- A valid iterator or pointer
An element
Or,Points to the position next to the last element
All the others are invalid.
The use of iterators
- Any type that has an iterator has a member that returns the iterator. Among them
begin
The end method returns an iterator that refers to the first element, and the end method returns a pointerThe next position of the trailing element
Iterator to the end. The empty containerBegin () and end ()
Return the same iterator. - When returning an iterator from a function, the type is used
auto
, regardless of the type of iterator. - Dereference is available
*
Access the element to which the iterator points, similar to a pointer. Attempt to dereferenceinvalid
orAfter the end of
Iterators are undefined. - Use with iterators
++
You can move to the next element. They are logically sequential and not necessarily spatially adjacent. - with
++, --, ==! =
To perform traversal operations, because these operations are valid on all container iterators. whileIndex and <, >
The equivalent operator is undefined in most container iterators. - The iterator type is corresponding to the container type
iterator
andconst_iterator
The former can be read and written while the latter can only be read. Type writing is as followsvector<int>::iterator
. Each container defines a type called iterator. - If the object inside the container is a constant
The begin and end
returnconst_iterator
Iterator, otherwise returnsiterator
The iterator - Cbegin and CEND methods return for any container
const_iterator
The iterator - Called by iterator
Element a member of the object
“, using such as(*it).function()
Otherwise, it fetches the member and dereferences it. - A simplified version can also be used when calling members of an element object through iterators
->
Operator, which combines the dereference and fetch operations,it->function()
Is equivalent to(*it).function()
- Any possible
Changing container capacity
Operations, such aspush_back
, invalidate the iterator of the container.
Examples of iterator use:
vector<int> v; For (int n = 0; //v is an array of variables of type int. n<5; ++n) v.push_back(n); //push_back adds an element to the end of the vector. Vector <int>::iterator I; // define the forward iterator for (I = v.box (); i ! = v.end(); Cout << * I << ""; //* I is the element referred to by iterator I * I *= 2; } cout << endl; For (vector<int>::reverse_iterator j = v.rbegin(); j ! = v.rend(); ++j) cout << *j << " ";Copy the code
Iterator operation
string
andvector
They are sequential, so their iterators support more operations, such as iterator operations, that allow iterators to move across more than one element at a time, and to compare the size of iterators.- Iterators and integer values can be added or subtracted, and the return value is an iterator that moves several positions forward or backward.
- Relational operators can be used
> >=, <, <=
Compare the size of iterators - If we subtract iterators, the result is two iterators
distance
, refers to how far forward the right iterator can be moved to rematch the left iterator. The distance can be positive or negative. The type corresponds to the container typedifference_type
, is a signed integer.
An array of
- Arrays are also containers for objects of the same type, which have no names themselves and are accessed through locations in the array.
- Array size is fixed, cannot add elements. Performs better than containers such as vector.
Define and initialize an array
- An array is a compound type, declared as
int a[d];
, includinga
Is the name of the array,d
Is the size of the array. The array size is also part of the type, should be known at compile time, and must be a constant expression. - By default, array elements are
Default initialization
- When defining an array, write the type manually
auto
, but the availabledecltype
- You can do it with arrays
List initialization
, there is no need to specify the size manually.The list length is the array size
. If the size is specified manually, the size can only beGreater than or equal to
Initial value list size, with the initial value list initialization of the first element, the default initialization of the following. A character array
In particular, it can be initialized with a string literal and does not need to specify the size manually, in which case a null character is appended at the end.
char a1[]={'C','+','+'}; Char a1[]={'C','+','+','\0'}; char a1[]={'C','+',' \0'}; // list initialization, empty character char a3[]="C++"; // initialize the string literal, empty character const char A4 [6]="Daniel"; // There is no space for empty charactersCopy the code
You cannot copy an array to another array as an initial value, nor can you assign to an array from an array
. Because the array name is the address of the first element, it does not represent the entire array.
Array-related compound definitions:
int arr[10]; int *ptrs[10]; // An array of Pointers. Int refs[10]=/*? Int (*Parray)[10]=&arr; // An array pointer. Int (&arrref)[10]=arr; int (&arrref)[10]=arr; // Array reference. Int *(&arry)[10]= PTRS; int *(&arry)[10]= PTRS; // A reference to an array of Pointers. Is a reference to an array of length 10, and the element is a pointer to an intCopy the code
Accessing an array element
- Array available range
for
Or subscript access - When using an array subscript, it is defined as
size_t
Type, this is machine dependentunsigned
Type, sufficient to represent the size of any object in memory, incstddef
Defined in header files. - Subscripts for arrays are defined by the C++ language, and subscripts for containers such as vectors are defined by the library.
Pointers and arrays
- When you use an array name, the compiler usually converts it to
Pointer to the first element
. - Addresses are used for array elements
&
Can get its pointer manually - When the array name acts as
Auto Initial value of the variable
When, out ofTypes are Pointers
It’s not an array, it’s like taking the address of the first element and giving it the initial value. But withdecltype
Phi, I get phiAn array type
. - Pointers are also iterators. String and vector iterators support operations supported by array Pointers.
- with
begin
andend
Gets the pointer to the first element and the pointer to the last element of the array, defined in the iterator header file. Because arrays are not classes, they are not member methods - The result of subtracting two Pointers is of type
ptrdiff_t
, defined in the cSTddef header, is a signed type. - Pointer operations and subscripts: expressions
*(ia+4)
Compute and dereference the new address of pointer ia after 4 elements forward,Equivalent to the ia [4]
- Pointers can use subscripts.
In fact, we use a subscript for an array, but we use a subscript for a pointer to the first element
. At this point, the compiler converts the array name to a pointer to the first element, and then applies subscripts to the pointer. - In the standard library
The iterator subscript must be unsigned
, butPointer subscripts are built-in in C++
, can be handlednegative
, i.e.,Pointers accept signed subscripts
Multidimensional array
- C++ doesn’t have multidimensional arrays.
A multidimensional array is an array of arrays
. - For a two-dimensional array, the first dimension is a row and the second dimension is a column
- Arrays can be initialized with a list, and curly braces can be nested or not. 0 because arrays are stored contiguously (automatic 0 is the defined dimension size)
- Example: Definition of a multidimensional array
Int ia [3] [4] =,1,2,3,4,5,6,7 {0}; // Ia is a 3-element array. Each element is a 4-element array. Ia has three rows and four columns. Int ib[3][4]={{0},{4},{8}}; // Ib is a 3-element array. Each element is a 4-element array. Ia has three rows and four columns. Int (&row)[4]=ia[1] // Row is a reference to a 4-element array of type int that is initialized as the second row of IACopy the code
- If you use
Range for loop
collocationauto
To iterate through or modify a multidimensional array, except for the innermost loop, the auto element should be of reference type.
Int a [3] [4],3,5,6,6,3,5,6,8,9,4,6 {1}; For (auto &row: a){cout << row << endl; cout << row << endl; For (auto &num: row){cout << "num: "<< num << endl; }} // Change the element size_t CNT =0; For (auto &row:ia){// For (auto &row:ia){for(auto &row:ia){// For (auto &row:ia){for(auto &row:ia){// For (auto &row:ia){col= CNT; // Modify element ++ CNT; }} // print element for(const auto &row:ia) // Avoid auto for(auto col:row) // Inner loop is an element is not an array, there is no problem with auto as a pointer cout<<col<<endl; For (auto row:ia) // Ia is used as a pointer type by auto for(auto col:row) // Error, pointer cannot be traversedCopy the code