当前位置:网站首页>[notes on c++ primer] Chapter 3 string, vector and array

[notes on c++ primer] Chapter 3 string, vector and array

2022-06-27 07:50:00 Little silly bird_ coding

 Insert picture description here

Author's brief introduction : Bo Lord stay read machine device people study investigate raw , Objective front study One . Yes meter count machine after End sense xing boring , xi huan c + + , g o , p y t h o n , Objective front Ripe Learned c + + , g o language said , Count According to the library , network Collateral Ed cheng , 了 Explain branch cloth type etc. phase Turn off Inside Rong \textcolor{orange}{ The blogger is studying robotics graduate , Currently, Yanyi . Interested in the back end of the computer , like c++,go,python, Currently familiar with c++,go Language , database , Network programming , Understand the distribution and other related contents } Bo Lord stay read machine device people study investigate raw , Objective front study One . Yes meter count machine after End sense xing boring , xi huan c++,go,python, Objective front Ripe Learned c++,go language said , Count According to the library , network Collateral Ed cheng , Explain branch cloth type etc. phase Turn off Inside Rong
individual people Lord page : \textcolor{gray}{ Personal home page :} individual people Lord page Little silly bird _coding
the a : \textcolor{gray}{ Support :} the a : Such as fruit sleep have to Bo Lord Of writing Chapter also No wrong or person you use have to To Of word , can With Exemption fee Of Turn off notes One Next Bo Lord , Such as fruit 3、 ... and even closed hidden the a Just more good La \textcolor{green}{ If you think the blogger's article is good or you can use it , You can follow the blogger for free , It would be better if the three collections support } Such as fruit sleep have to Bo Lord Of writing Chapter also No wrong or person you use have to To Of word , can With Exemption fee Of Turn off notes One Next Bo Lord , Such as fruit 3、 ... and even closed hidden the a Just more good La Just yes to Give I most Big Of the a ! \textcolor{green}{ Is to give me the greatest support !} Just yes to Give I most Big Of the a
Abstract of this article

This column is mainly about c++ primer The summary of this Bible , And relevant notes for each chapter . I am reviewing this book now . At the same time, I hope I can help you , After learning this book . This article mainly explains the 2 Chapter Variables and basic types

The first 3 Chapter character string 、 Vectors and arrays

String、vector Are the two most important types of standard libraries ,String Support Variable length string ,vector Support Variable length set

An iterator is a type of string and vector Supporting standard library types . Commonly used for access string Characters or... In vector The elements in

Built in arrays are a basic type ,string and vector Are some kind of abstraction of it .

3.1 Namespace using Statement

  • Use a namespace : for example using std::cin Indicates the use of a namespace std The name of cin.
  • The header file should not contain using Statement . In this way, the source code that uses the header file will also use this declaration , For some programs , There may be name conflicts , Bring risks .
using std::cin;

3.2 Standard library type string

  • Standard library type string Represents a variable length sequence of characters .
  • string Defined in the namespace std in .( Include header file )
  • string object : Different from string literals .
#include <string>
using std::string

3.2.1 Definition and initialization string object

string The default initialization is an empty string
initialization string How objects work :

Initialization mode explain
string s1 Default initialization ,s1 Is an empty string
string s2(s1)s2 yes s1 Copy of
string s2 = s1 Equivalent to s2( s1 ),s2 yes s1 Copy of
string s3(“value”)s3 It's the face value “value” Copy of , Except for the last empty character of the literal value
string s3 = “value” Equivalent to s3(“value”),s3 It's the face value “value” Copy of
string s4(n, ‘c’) hold s4 Initialize to continuous n Characters c A string of

Be careful :

  • When copying , Does not contain the last empty string
  • Initialize with string literals or character arrays string Object time ,string Object does not contain a null character at the end , It removes empty characters from the end of the character array .

Initialization mode

  • Copy initialization
  • Direct initialization
  • List initialization
string s5 = "hello";           // Copy initialization 
string s6("hello");            // Direct initialization 
string s7{
    hello};              // List initialization 

3.2.2 string Operations on objects

string Common operations

string Common operations
getline(is, s) from is To read a line to s, return is (is It's the input stream )
s.empty()s Empty return true, Otherwise return to false
s.size() return s The number of characters in
s[n] return s pass the civil examinations n Character reference , Location n from 0 Count up
s1+s2 return s1 and s2 The result of the connection
s1=s2 use s2 In place of s1 Characters from Central Plains
s1==s2 If s1 and s2 The characters contained in the are exactly the same , Then they are equal ;string The equality judgment of objects is sensitive to the case of letters
s1!=s2 ditto
<, <=, >, >= Use the order of characters in the dictionary to compare , And sensitive to the case of letters ( Compare the first different position )

Be careful :

  • adopt cin >> string, In the reading string Object time ,string Object automatically ignores the leading whitespace ( Space 、 A newline 、 etc. ) And start reading from the first real string , Until you meet the next blank , So it can't be used cin Read sentences , But it can. Read the words ;
  • String literals and string There are two different types
string s;
cin >> s;             // Input hello world
cout << s << endl;    // Output is hello
 

Reading and writing string object

Use cin and cout Read and write string object

Use getline Function reads a line

  • getline() Function defined in The header file string in
  • getline() The parameters are an input stream and a string object , Function to read from a given input stream , Know where line breaks are encountered ( Note that the newline character is different from the white space character above
  • Read to end of file
    Be careful :getline Will also read line breaks into , But do not store newline characters in string object . Trigger getline() The newline returned by the function is actually discarded . Got string Object does not contain a newline character .
string s;                // Read to end of file 
while(getline(cin, s))   // Input is hello world
	cout << s << endl;     // Output is hello world

string::size_type type

  • string Medium size() The return value type is string:: size_type
  • string::size_type Is an unsigned value , Can save any string Size of object , So it is used to store string Class size Function returns the variable of the value , All should be string::size_type Type of
  • c++11 It is allowed to use auto and declltype To get this type
  • In specific use , Indicate by scope operator size_type It's in class string As defined in .
auto len = s.size();// len  The type is  string::size_type

Be careful : There is already... In an expression size() function , Don't use it int 了 , This can avoid mixing int and unsigned There may be problems .

Two string Add objects

  • Two string Objects are added to get a new string object , Its content is to connect the operator object on the left and the operator object on the right in series
string s1 = "hello,";
string s2 = "world";
string s3 = s1 + s2;
cout << s3 << endl;   //hello,world

Literal sum string Add objects

  • Remember the literal value and string It's different
  • The literal value is divided into : Character literals and string literals

Two string Add objects

string s1 = "hello,";
string s2 = "world";
string s3 = s1 + s2;
cout << s3 << endl;   //hello,world

string Object and character literals are added

  • When put string When objects and character literals are mixed , Every addition operation must be guaranteed (+) The operands on both sides of At least one is string
string s4 = s1 + ","               // correct , On the left string object , On the right is the character literal 
string s5 = "hello" + ","          // error , Both sides are character literals 

string s6 = s1 + "," + "world"     // correct 

string s7 = "hello" + "," + s1     // error , Two literal values cannot be added together 
// Equivalent to string s7 = ("hello" + ",") + s1

3.2.3 Handle string Characters in objects

cctype The following standard library functions are available in the header file to handle string The characters in .

cctype Functions in header file explain
isalnum(c) When c When it is a letter or a number
isalpha(c) When c True when it's a letter
iscntrl(c) When c True when is a control character
isdigit(c) When c It is true when it is a number
isgraph(c) When c True when it is not a space but can be printed
islower(c) When c True if it is a lowercase letter
isprint(c) When c True when is a printable character
ispunct(c) When c True if it is a punctuation mark
isspace(c) When c It is true when it is blank ( Space 、 Horizontal tabs 、 Vertical tabs 、 A carriage return 、 A newline 、 Paper in )
isupper(c) When c True if it is a capital letter
isxdigit(c) When c True if it is a hexadecimal digit
tolower(c) When c It's capital letters , Output the corresponding lowercase letters ; Otherwise output as is c
toupper(c) When c It's lowercase , Output corresponding capital letters ; Otherwise output as is c

Suggest : Use c++ Version of the standard library header file , namely cname Instead of name.h Type of header file .cname The names in the header file all belong to the namespace std;

Range for loop

  • for (auto c : str)
  • for (auto &c : str)
string str("hello world");
for(auto c:str)         //  about str Each character in 
    cout << c << endl;  //  Output the current character , Followed by a line break  hello world
  • When you want change string Value in object when , You need to define the loop variable as Reference type . Must be added through the display & Symbols to declare reference types .
  • Can't be in range for Statement to change the size of the traversed sequence .
for(auto &c:s)
    c = toupper(c);     //  Lower case to upper case 

visit string A character in , There are two ways 1. Can pass [ ], 2. You can use iterators

  • s[0] Represents the first character
  • s[size() - 1] Represents the last character
  • string The subscript of the object is from 0 Start to size() - 1 end
  • Index must be greater than or equal to 0 Less than size, Before using the index, it is better to use if(!s.empty()) Check whether the string is empty .
  • Any expression can be used as an index as long as it is an integer value . The index is an unsigned type size_type;

3.3 Standard library type vector

  • vector It's a Class template Not the type ,vector Is a type .
  • vector It's also a Containers , It can accommodate various data types
  • Itself is a class template , But you can instantiate a class

3.3.1 Definition and initialization vector object

vector <int>  v1;                 //vector The default initialization is a 0.
vector<string> v2(v1);            // v2=v1
vector<string> v2 = v1;           // Equivalent to v2(v1)
vector<string> v3(10,"dainian");  // 10 individual string
vector<string> v4(10);            // 10 Empty string

vector<string> v5{
    "a","hahah"};    //  List initialization 
vector<string> v5 = {
    "a","hahah"}; // Equivalent to above 

List initialization

  • Use a pair of {} To represent list initialization , The initialization process will try to treat the values in curly braces as a list of initial values .
  • If the value in curly braces cannot be used for list initialization , For example, to a string Of vector initialization , But the value in curly braces is an integer
vector<string> v {
    10};              // v  Yes  10  A default initialized element 
vector<string> v {
    10, "hello"};  // v  Yes  10  The values are  "hi"  The elements of 

Value initialization

If vector The element of the object is a built-in type , such as int Then the initial value of the element is 0, If it's a class type , Class is initialized by default .

3.3.2 image vector Object

  • v.push_back(e) Add elements to the tail .
  • In order to make vector Efficient growth , Usually an empty... Is defined first vector, Then it will be faster to add elements .
  • If you insert vector The initial values in are the same. At this time, it will be faster to determine the size and value during initialization , If the initial values are different , Even if the size is known , It is better to define an empty vector, Add more elements .

3.3.3 other vector operation

v.size();            // return v The number of elements in 
v.empty();           // If v Does not contain any elements , Return to true ; Otherwise return false 
v.push_back(t);      // towards v Add a value of t The elements of 
v[n]                 // return v pass the civil examinations n A reference to an element at a location 
v1 = v2				 // use v2 Copy and replace elements in v1 The elements in 
v1 = {
    a,b,c...}      // Replace... With a copy of the elements in the list v1 The elements in 
v1 == v2             // v1 and v2 Equal if and only if they have the same number of elements and have the same element value at the corresponding position 
v1 != v2
<,<=,>, >=	         // Compare in dictionary order 

  • You can use the range for statement vector Elements of sequence , Range for Statement should not change the size of its traversal sequence .
  • vector object ( as well as string object ) The subscript operator for , Subscript operations can only be performed on elements that are known to exist ( Only elements can be accessed , Or change an existing element ), however Cannot be used to add elements .

3.4 Iterator Introduction

  • All standard library containers can use iterators , But only a few support subscript operations at the same time , If it's a container , Try to operate with iterators
  • Similar to pointer type , Iterators also provide indirect access to objects .( You can access an element , You can also move iterators , Like a pointer )
  • Iterators are divided into valid and invalid .

3.4.1 Using Iterators

  • begin Returns the iterator pointing to the first element
  • end Returns an iterator that points to the next bit of the last element ( It is often called a tail iterator )
auto b = v.begin(), e = v.end()    // The return is iterator type 
auto c = v.cbegin(), f = v.cend()   // The return is const_iterator type 

Be careful : If the container is empty , be begin and end The same iterator is returned , Are all tail iterators

Iterator operator

Operator explain
*iter Return iterator iter The point is Reference to element
iter->mem Equivalent to (*iter).mem
++iter Make iter Indicates the next element in the container
- -iter Make iter Indicates the previous element in the container
iter1 == iter2 Determine if two iterators are equal
iter1 != iter2 Determine whether two iterators are not equal

Iterator type

There are two types of iterators :

  • terator
  • const_iterator
vector<int>::iterator it;       //it Be able to read and write 
string::iterator it;

vector<int>::const_iterator it; //it Only read 
string::const_iterator;

begin and end return type

  • begin and end The specific type of the return value is determined by whether the object is a constant , If the object is a constant ,begin and end return const_iterator, Otherwise, vice versa .
vector<int> v;
const vector<int> v1;
auto it = v.begin();  //it The type is iterator
auto it1 = v1.begin(); //it1 The type is const_iterator

Be careful : Where iterators are used to loop , Do not add or remove elements to the container to which the iterator belongs , You can change the element , Duze , The iterator doesn't know which element to point to , The iterator will fail

Iterator operation
string and vector Supported iterative operations . Note that you cannot add two iterators .
vector and string Operations supported by iterators :

Operator explain
iter + n The iterator adds an integer value and still gets an iterator , The new position indicated by the iterator moves several elements forward compared with the original position . The result iterator or indicates an element in the container , Or indicate the next position of the container tail element .
iter - n The iterator subtracts a certificate and still gets an iterator , The new position indicated by the iterator is moved back several elements . The result iterator or points to an element in the container , Or indicate the next position of the container tail element .
iter1 += n Compound assignment statement of iterator addition , take iter1 Add n The result of the assignment to iter1
iter1 -= n Compound assignment statement of iterator subtraction , take iter2 reduce n Add to iter1
iter1 - iter2 The result of subtracting two iterators is the distance between them , in other words , Move the iterator on the right side of the operator forward by two elements to get the iterator on the left . The two iterators involved in the operation must point to the next position of the element or tail element in the same container .
>、>=、<、<= The relational operator of the iterator , If an iterator
  • difference_type: Be sure to be large enough to store the distance between any two iterator objects , Positive but negative .
  • Iterators only subtract , No addition .

3.5 Array

  • Size of array , Fixed length , You can't change , amount to vector Low level version of

3.5.1 Define and initialize built-in arrays

  • The dimension of the array must be a constant expression
int a[0];                    // The dimension of the array must be a constant expression 
unsigned cnt = 42            // Not a constant expression 
constexpr unsigned cnt = 42; // It's a constant expression 
string strs[get_size()];     // When get_size() yes constexpr when , It's a constant expression 
  • Array and vector The element of must be an object , Cannot be a reference
  • Arrays can't use auto The key is to infer the type from the initial value list

The particularity of character array

char a1[] = {
    'c','+', '+' };   // List initialization , There are no empty characters , Dimension is 3
char a2[] = "c ++";            // There is an empty string , Dimension is 4;
const char a4[3] = "c++";      // error , There is no space for empty characters 

You cannot assign or copy an array to another array . You can copy by element , But you can't copy the entire array directly .

Understand complex array declarations

Because the array itself is an object , So it is allowed to define array pointers and array references .

It is easy to understand the order from the name of the array to the right inside out

int *ptr[10];           // ptrs It's one that contains 10 An array of integer pointers 
int (*ptr)[10] = &arr;  // ptrs It's a pointer , Point to a containing 10 Array of integers 
int (&ptr)[10] = &arr;  // ptrs It's a reference , Contain a reference to 10 Array of integers 

for example :

  • First reading (),*ptr It's a pointer , Looking to the right , This pointer points to an array , Looking to the left , This array is int Type , therefore int (*ptr)[10] = &arr; ptrs It's a pointer , Point to a containing 10 Array of integers

3.5.2 Accessing array elements

  • Array elements can use ranges for sentence perhaps Subscript operator To visit
  • When using array subscripts , Usually defined as size_t type ( Is an unsigned type , It is designed to be large enough to represent the size of any object in memory )

Array comparison vector What are the disadvantages of

  • The size of the array is determined .
  • Do not add elements at will .
  • Copy and assignment are not allowed .
    Arrays cannot be copied directly , Instead, you need a copy of each element . and vector It can be copied directly
	// The array requires each element to be copied 
    int arr[10];
    for (int i = 0; i < 10; ++i) arr[i] = i;
    int arr2[10];
    for (int i = 0; i < 10; ++i) arr2[i] = arr[i];
    
    //vector It can be copied directly 
    vector<int> v(10);
    for (int i = 0; i != 10; ++i) v[i] = arr[i];
    vector<int> v2(v);
    for (auto i : v2) cout << i << " ";

3.5.3 Pointers and arrays

  • In most cases , An object that uses an array type actually uses a pointer to the first element of the array
  • Standard library type ( Such as string、vector etc. ) All subscripts of are unsigned , The built-in subscript of the array does not have this requirement .
  • A pointer to an array element is equivalent to vector Iterators in
  • Pointer access array : When using array names in expressions , The name is automatically converted to a pointer to the first element of the array .
  • When using arrays , The compiler usually converts it into a pointer .

3.5.4 c Style string

  • c++ By c inherited c Style string
  • c Style string It's not a type , It's a way of writing , It is a conventional way of writing to express and use strings .
  • The string written according to this habit is stored in the character array with Null character ('\0') end .
  • c++ Support c Style string , But it's best not to use , It is very easy to cause program vulnerabilities , For most applications , Use standard library string Than using C Style strings are safer 、 More efficient .
function Introduce
strlen(p1) return p1 The length of , Empty characters are not counted
strcmp(p1, p2) Compare p1 and p2 Equality of . If p1==p2, return 0; If p1>p2, Returns a positive value ; If p1<p2, Returns a negative value .
strcat(p1, p2) take p2 Attach to p1 after , return p1
strcpy(p1, p2) take p2 Copy to p1, return p1
  • The functions listed in the above table are not responsible for verifying their string parameters
  • The pointer to the passed in parameter must point to a null terminated array . You must ensure that the array is large enough .
char ca[] = {
    "hello", "world"}   // Do not end with a null character 
cout << strlen(ca) << endl;      // error :ca Does not end with a null character 

about string, have access to s = s1 + s2,s1 > s2 Add and compare , and c The style string does not work , Because they are actually pointers .

3.5.5 Interface with old code

string Objects and C Mixing of style strings

  • You can use string literals to initialize string Object or with string Object addition , All places where a string literal can be used can be replaced by an array of characters that end with a null character .

  • The reverse cannot be used string Object initializes the character array , It must be used. c_str() Function will string Object to c Style string

string s ("hello world");
const char *str = s;          // error , Out-of-service string Object initialization char* 
const char* cp = s.c_str();  // s.c_str()  Returns a pointer to a character array that ends with a null character . 

Initialize with an array vector object

  • It is not allowed to use an array to assign a value to an array of another built-in type
  • You can use arrays to initialize vector object , Use two pointers to indicate the range ( Left closed interval )
int arr[] = {
    0, 1, 2, 3, 4, 5}; 
vector<int> ivec(begin(arr), end(arr));              


Not recommended c Style strings and built-in values , All use standard library containers

3.6 Multidimensional arrays

Strictly speaking C++ There is no multidimensional array in , That's actually an array of arrays .

int arr[20][30][40]   // Initialize all elements to  0

Initialization of multidimensional array

// Show all elements initialized 
int a[3][4] = {
    1,2,3,4,5,6,7,8,9,10,11,12}
int a[3][4] = {
    {
    1,2,3},{
    4,5,6},{
    7,8,9},{
    10,11,12}}  // The same thing as above 

// Show initialization part elements 
int a[3][4] = {
    {
    0},{
    1},{
    2}};  // Just initialize the first element of each line 

Subscript reference of multidimensional array

int arr[3][4];
arr[0];// This is a one-dimensional array with four elements 
arr[0][0];// The elements in the first row and the first column 

Using range for Statement handles multidimensional arrays

  • c ++11 Can be used in for Statement handles multidimensional arrays .
  • Pay attention to the scope for Change the element value in the statement to show the use of & The symbol is declared as a reference type .
  • Pay attention to the scope of use for When looping through multidimensional arrays , Except for the innermost cycle , All other loop control variables should be of reference type .
  • Because if it is not declared as a reference type , The compiler will automatically convert the control variable to a pointer to the first element of the array , Can not continue to use the scope in the inner layer for Loop through the control variable .
constexpr size_t rowCnt = 3, colCnt = 4;
int ia [rowCnt][colCnt];

for(auto& row : arr)          // Assign values to each row 
    for(auto col : row)       // Assign values to each column , For example, assign values first [0][0],[0][1],[0][2]

Output arr There are four ways to get the element of

  • Range for sentence - Do not use type aliases
  • Range for sentence - Use type aliases
  • Ordinary for loop
  • The pointer
//  Range  for  sentence - Do not use type aliases 
for (const int (&row)[4] : arr)
    for (int col : row)
        cout << col << " ";
cout << endl;

//  Range  for  sentence - Use type aliases 
using int_array = int[4];
for (int_array &p : ia)
    for (int q : p)
        cout << q << " ";
cout << endl;

//  Ordinary  for  loop 
for (size_t i = 0; i != 3; ++i)
    for (size_t j = 0; j != 4; ++j)
        cout << arr[i][j] << " ";
cout << endl;

//  The pointer 
for (int (*row)[4] = arr; row != arr + 3; ++row)
    for (int *col = *row; col != *row + 4; ++col)
        cout << *col << " ";
cout << endl;


The pointer vs quote

  • A reference always points to an object , It is wrong to define a reference without initialization .
  • Assign a value to the reference , What is modified is the value of the object associated with the reference , Instead of associating a reference with another object

The dynamic array

  • Use new and delete Expression and c in malloc and free Similar functions , That is, on the heap ( Free storage area ) Allocate storage space in .
  • Definition : int *pia = new int[10]; 10 Can be replaced by a variable .
  • Release : delete [] pia;, Be careful not to forget [].
原网站

版权声明
本文为[Little silly bird_ coding]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270742069530.html