当前位置:网站首页>Summary of string, vector and array learning

Summary of string, vector and array learning

2022-06-13 09:33:00 Ritian juvenile wzh

character string (string), vector (vector) And an array

string and vector Are the two most important types of Standard Libraries ,string Support variable length strings ,vector Represents a variable length collection array , Iterators in the standard library types that match them , Belong to string and vector The matching type of , Frequently used to access string Characters in or vector The elements in

Namespace using Statement

stay C++ In the preliminary study of , We often type such a piece of code ,

using namespace std;

At the beginning of the study , We don't know what it means , You just need to understand and knock

Simply speaking , up to now , The library functions we can use now basically belong to the namespace std, namely C++ Standard library , The program also explicitly expresses this .

for example :

If you don't want to type this code using namespace std; While using cin function (cin Read from standard input ), The scope operator... Is used here (::) The meaning of : The compiler should look for that name from the scope shown by the name on the left side of the operator .

therefore ,std::cin It means to use a namespace std The name of cin.

With using The declaration does not need a special prefix ( Like a namespace ::) You can also use the name you want .

using The declaration takes the form of :

using namespace::name;

Once the above statement is declared , You can directly access the names in the namespace ;

1. Don't use using Declared code :

#include<iostream>

int main()
{
	int ans;
	std::cin>>ans;
	std::cout<<ans<<std::endl;
	return 0;
}

2. Use using Declared code :

#include<iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
	int ans;
	cin>>ans;
	cout<<ans<<endl;
	return 0;
}

notes : In accordance with the relevant provisions , Every using Declare to introduce a member in the namespace

The header file should not contain using Statement

Code located in header files should not generally use using Statement . This is because the contents of the header file will be copied to all files that reference it , If there is something in the header file using Statement , Then every file that uses the header file will have this declaration . For some programs , Due to the inadvertent inclusion of some names , Instead, there will be some unexpected name conflicts

** matters needing attention :**using Declare the scope rules followed by the imported name : Its effective range ranges from using Where the declaration begins , Until using The scope of the declaration ends

using instructions

using instructions (using directive) and using Statement A similar place is , We can use the shorthand form of namespace names ; however , and using The difference is , We have no control over which names are visible , Because all names are visible .

using Indicate with keyword using Start , And then keyword namespace as well as The name of the namespace ( The three most )

for example :

using namespace std;

using Indicates that all names in a particular namespace are visible , So we don't have to add any prefix qualifiers to them .

Abbreviated names from using Instruct to begin , Until using Indicates that the end of the scope can be used

3. Use using Indicated code :

#include<iostream>
using namespace std;

int main()
{
	int ans;
	cin>>ans;
	cout<<ans<<endl;
	return 0;
}

Standard library type string

Standard library type string Represents a variable length sequence of characters , Use string The type must first contain string The header file

** The header file :#include< string > **

notes : C++ On the one hand, the standard specifies the operations provided by the library type , On the other hand, some performance requirements are made for the implementer of the library . therefore , Standard library types are efficient enough for general applications .

Definition and initialization string object

How to initialize string The object of the class is composed of string Class itself .

string Class provides many kinds of initialization string Class , But there must be a difference between these methods : For example, the number of initial values is different , Or the type of initial value is different

initialization string The most common way for objects :

string s1;        //  Default initialization ,s1 It's an empty string 
string s2=s1;     // s2 yes s1 Copy of 
string s3="CPP";  // s3 Is a copy of the literal value of the character 
string s4(5,'C'); // s4 The content is CCCCC

The code is as follows :

#include<iostream>
#include<string>
using namespace std; //  Use using instructions  

int main()
{
	string s1;        //  Default initialization ,s1 It's an empty string 
	string s2=s1;     // s2 yes s1 Copy of 
	string s3="CPP";  // s3 Is a copy of the literal value of the character 
	string s4(5,'C'); // s4 The content is CCCCC
	// ends -  Insert empty character , And then refresh ostream buffer 
	// endl -  Insert newline , And then refresh ostream buffer  
	cout<<s1<<ends<<s2<<ends<<s3<<ends<<s4<<endl;
	return 0;
}
initialization string How objects work
Initialization mode explain
string s1 Default initialization ,s1 It's an empty string
string s2s2 yes s1 Copy of
string s3(“NewThread-CPP”)s3 It's the face value "value" Copy of , Except for the last empty character of the literal value
string s3 = “NewThread-CPP” Equivalent to s3(“NewThread-CPP”),s3 It's the face value "NewThread-CPP" Copy of
string s4(n,‘C’) hold s4 Initialize to continuous n Characters C A string of
Direct initialization and copy initialization
  • If you use the equal sign (=) Initialize a variable , It's actually executing Copy initialization (copy initialization), The compiler copies the initial value to the right of the equal sign into the newly created object
  • If you don't use the equal sign , Then it is executed Direct initialization (direct initialization)
string s1 = "NewThread-CPP"; // Copy initialization 
string s2("NewThread-CPP");  // Direct initialization 
string s3(10,'C');           // Direct initialization 

Objective to , Direct initialization is more efficient than copy initialization

string Operations on objects

string The operation of :

operation explain
os<<s take s Write output stream os in , return os
is>>s from is Read string assigned to s, Strings are separated by whitespace , return is
getline(is, s) from is To read a line to s, return is
s.empty() if s Returns... For an empty string 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 Start counting
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 are exactly the same , Then they are equal ;string The equality judgment of objects is sensitive to the case of letters
s1!=s2
<,<=,>,>= Use the order of characters in the dictionary to compare , And sensitive to the case of letters
Read an unknown number of string object

The following code can read an unknown number of characters :

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string word;
	while(cin>>word)       //  Read over and over again , Until the end of the file  
		cout<<word<<endl;  //  Output words one by one , Each word is followed by a newline  
	return 0;
	//  Input Crtl+Z You can end the cycle and exit the program  
}

notes : This loop condition is responsible for monitoring the flow when reading , If the input stream is valid , That is to say, there is no end of file mark or illegal input , Then perform while Statement internal operation .

Use getline Read a whole line

If we want to keep the blank character in the final string , It's time to use getline function Replace the original >> Operator .

getline function The parameters of are an input stream and a string object , Function to read from a given input stream , Until a newline is encountered ( Notice that line breaks are also read in ), Then put the reading into that string Go to the object ( Be careful not to save line breaks ).

getline As soon as a newline character is encountered, the read operation ends and the result is returned , Even if the input starts with a newline character . If the input really starts with a newline character , Then the result is empty string

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string line;
	//  Read in one line at a time , Until the end of the file  
	while(getline(cin,line))
		cout<<line<<endl;
	return 0;
 } 

** notes :** Trigger getline The newline returned by the function is actually discarded , Got string Object does not contain the newline character

string Of empty and size operation

empty Functions are based on string Whether the object is null returns a corresponding Boolean value , Rewrite the original program :

//  Read in a whole line at a time , If you encounter an empty line, skip directly 
while(getline(cin,line))
    if(!line.empty())
        cout<<line<<endl;

size The function returns string Length of object ( namely string The number of characters in the object ), have access to size Function only outputs a length greater than n Character lines :

string line;
//  Read in a whole line at a time , The output exceeds n Character lines 
while(getline(cin,line))
    if(line.size()>n)
        cout<<line<<endl;
string Comparison of objects (< , <= , > , >= , == , !=)

The relational operator follows ( case-sensitive ) Dictionary order rules :

  1. If two string Objects have different lengths , And shorter string Each character of the object is associated with a longer string The characters in the corresponding position of the object are the same , It is shorter string The object is smaller than the length string object
  2. If two string Objects are inconsistent in some corresponding positions , be string The result of object comparison is actually string The result of the comparison of the first pair of different characters in the object
Two string Add objects

Two string Objects are added to get a new string object , Its content is to connect the operation object on the left side with the operation object on the right side in series .

Yes string Object uses the addition operator (+) The result is a new string object , The characters it contains consist of two parts : The first half is the plus sign to the left string The characters contained in the object , The second half is the plus sign to the right string The characters contained in the object

string s1="NewThread ", s2="CPP\n";
string s3=s1+s2;

Compound assignment operator (+=) Be responsible for turning the right string The contents of the object are appended to the left string Behind the object

s1 += s2; //  Equivalent to s1 = s1+s2
Literal sum string Add objects

The standard library allows you to convert character literals and string literals to string object , All in need string Object can be replaced by these two literals .

Code case :

string s1 = "NewThread",s2 = "CPP";
string s3 = s1 + "," + s2 + "\n";
string s4 = s1 + "!"; //  correct : Put one string Object is added to a literal 
string s5 = "NewThread" + "!"; //  error , Both operands are not string
//  correct , Each addition operator has an operand that is string
string s6 = s1 + "CPP";
string s7 = "NewThread" + "," + s2; //  error : You can't add literal values directly 

** notes :** For some historical reasons , Also for the sake of C compatible , so C++ String literals in languages are not standard library types string The object of .

Bear in mind , String literals and string It's a different type

practice :

​ Write a program to read two strings , Compare whether they are equal and output the result . If it's not equal , Output the larger string . Rewrite the above procedure , Compare whether the two input strings are equal in length , If it's not the same length , Output the string with larger length .

answer :

​ The procedure for comparing string sizes is as follows :

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1,s2;
	cout<<" Please enter two strings :"<<endl;
	cin>>s1>>s2;
	if(s1==s2)	
		cout<<" Two strings are equal "<<endl;
	else if(s1>s2)
		cout<<s1<<" Greater than "<<s2<<endl;
	else
		cout<<s2<<" Greater than "<<s1<<endl;
	return 0;
 } 

​ The procedure for comparing string lengths is as follows :

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1,s2;
	cout<<" Please enter two strings :"<<endl;
	cin>>s1>>s2;
	auto len1=s1.size();
	auto len2=s2.size();
	if(len1==len2)
		cout<<s1<<" and "<<s2<<" It's all the length of "<<len1<<endl;
	else if(len1>len2)
		cout<<s1<<" Than "<<s2<<" The length of "<<len1-len2<<endl;
	else 
		cout<<s2<<" Than "<<s1<<" The length of "<<len2-len1<<endl;
	return 0;
 } 
Handle string Characters in objects

stay The header file cctype A set of standard library functions are defined in string This part of the work of the characters in the object

cctype Functions in header file :

function explain
isalnum When c When it is a letter or a number
isalpha When c True when it's a letter
iscntrl When c True when is a control character
isdigit When c It is true when it is a number
isgraph When c True when not blank but printable
isxdigit When c True if it is a hexadecimal letter
isprint When c True when is a printable character ( namely c Is a space or c In visual form )
ispunct When c True if it is a punctuation mark ( namely c Not a control character , Numbers , Letter , One of the printable blanks )
isspace When c It is true when it is blank ( namely c Is a space , Horizontal tabs , Vertical tabs , A carriage return , A newline , One of the paper feed symbols )
islower When c True if it is a lowercase letter
isupper When c True if it is a capital letter
tolower If c It's capital letters , Output the corresponding lowercase letters ; Otherwise output as is c
toupper If c It's lowercase , Output corresponding capital letters ; Otherwise output as is c

Case study :

1. Case conversion :

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
	string ans;
	cout<<" Please enter the word you want to enter :";
	cin>>ans;
	for(auto &s : ans) 
		if(islower(s))
			s = toupper(s);
	cout<<" The capitalized form of the word :"<<ans<<endl;
	for(auto &s : ans)
		if(isupper(s))
			s = tolower(s);
	cout<<" The lowercase form of the word :"<<ans<<endl;
	return 0; 
 } 

2. Read the number in the string :

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
	string str,ans;
	cout<<" Enter a string containing numbers :";
	cin>>str;
	for(auto s : str)
		if(isdigit(s))
			ans += s;
	cout<<" The number contained in the string :"<<ans<<endl;
	return 0;
 } 
Little knowledge : Use C++ Version of C Standard library header file

​ C++ In the standard library, except C++ The special functions of language , It's compatible with C The standard library of languages . stay C The header file in the language looks like name.h,C++ Then name these header files cname. That is to remove .h The suffix , In the file name name Letters were added before c, And here it is c It means that it belongs to C Language standard header file .

​ Generally speaking ,C++ The program should use the name cname Instead of using name.h In the form of , Names in the standard library are always in the namespace std Find .

How to better handle each character ?C++11 New characteristics , Use scope based for sentence ;

​ If you want to better handle string Object , Now the best way is to use C++11 A statement provided by the new standard : Range for(range for) sentence

​ This statement traverses each element in a given sequence and performs some operation on each value in the sequence , Its grammatical form :

for(declaration : expression)
	statement

among ,expression part It's an object , Used to represent a sequence .declaration part Responsible for defining a variable , This variable will be used to access the underlying elements in the sequence .

Every iteration ,declaration Some variables will be initialized to expression The next element value of the section

Use cases :

1. Use C++11 Scope of the new standard for sentence

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	cin>>str;
	for(auto s : str)
		cout<<s<<ends;
	return 0;
 } 

2. Use a regular loop for sentence

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string str;
	cin>>str;
	for(int i=0;i<str.size();i++)
		cout<<str[i]<<ends; 
	return 0;
 } 

How to use the scope for Statement to change characters in a string

​ If you want to change string The value of the character in the object , You must define the loop variable as a reference type , Its grammatical form is as follows :

for(auto& s : expression)
	statement

** notes :** A reference is just an alias of a given object , So when you use references as loop control variables , This variable is actually bound to each element of the sequence in turn . Use this reference , We can change the value of its binding .

Case study :

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
	string ans;
	cout<<" Please enter the word you want to enter :";
	cin>>ans;
	for(auto &s : ans) 
		if(islower(s))
			s = toupper(s);
	cout<<" The capitalized form of the word :"<<ans<<endl;
	return 0;
}
How to process only part of the characters ?

​ Want to visit string There are two ways for a single character in an object : One is Use subscript , The other is Using Iterators

** Subscript operator ( [] )** The input parameter received is string::size_type Type value ( namely unsigned Unsigned type ), This parameter indicates the position of the character to be accessed ; The return value is a reference to the character at that position

notes : Check the validity of the subscript

​ string The subscript of the object must be greater than or equal to 0 Less than s.size()

Subscripts outside this range will lead to unpredictable results , Deduce from this , Use subscript to access null string It can also lead to unpredictable results

Use subscripts to execute random access cases :

1. hold 0 To 15 Convert the decimal number between to the corresponding hexadecimal form :

#include<iostream>
#include<string>
using namespace std;

const string hexdigits = "0123456789ABCDEF"; //  Hexadecimal number 

int main()
{
	unsigned n;
	string ans;
	cout<<" Input 0~15 The numbers between are converted to the corresponding hexadecimal form :";
	while(cin>>n)
		if(n<hexdigits.size()) //  Ignore invalid output  
			ans += hexdigits[n]; //  Get the corresponding hexadecimal number  
	cout<<" Hexadecimal digits corresponding to significant digits :";
	for(auto s : ans)
		cout<<s<<ends;
	cout<<endl;
	return 0;
 } 

2. Using range for Statement to use... For all characters in a string X Instead of :

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s;
	cout<<" Please enter a string , Can contain spaces :"<<endl;
	getline(cin,s);
	for(auto &c : s)
		c = 'X';
	cout<<s<<endl;
	return 0;
 } 

3. Read in a string containing punctuation marks , Remove the punctuation marks and output the rest of the string :

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
	string ans;
	cout<<" Please enter a string with punctuation :";
	getline(cin,ans);
	for(auto s : ans) {
		if(ispunct(s))
			cout<<ends;
		if(!ispunct(s))
			cout<<s;
	}
	return 0;
 } 

Standard library type vector

Standard library type vector Represents a collection of objects , All of the objects are of the same type .

The header file :#include< vector >

Each object in the collection has a corresponding index , Index is used to access objects . because vector“ Holding ” Other objects , So it is often called Containers (container)

C++ Language has both Class template (class template), There are also function templates , and vector Is a class template

If you want to customize the template, you need to C++ Have a deeper understanding of , And we can simply use the class template prepared by the standard library for us

The template itself is not a class or function , contrary , You can think of the template as a description of the compiler generated classes or functions . The process by which a compiler creates a class or function from a template is called Instantiation (instantiation)

When using templates , You need to point out what type of class or function the compiler should instantiate , That is, the template name is followed by a pair of angle brackets , Put information in brackets

We use vector For example , Instantiation vector:

vector<int> ivec;          // ivec preservation int Object of type 
vector<Student> stu_vec;   //  preservation Student Object of type 
vector<vector<int>> iivec; //  The vector element is vector object , It's like a two-dimensional array 

** notes :**vector It's a template, not a type , from vector The generated type must contain vector The type of element in , for example vector< int >

vector Can accommodate most types of objects as its elements , But because references are not objects , So there is no such thing as vector

** matters needing attention :** Some compilers may still need to handle elements with old-fashioned declaration statements vector Of vector object , Such as vector<vector<int> >

The purpose of this study is to make you get used to vector< int > Operation in place of array ,vector< T > The relevant in-depth study will be carried out by you

Definition and initialization vector object

​ Like any kind of type ,vector Templates control how vectors are defined and initialized

initialization vector Object method :

initialization Related explanations
vector< T > v1v1 It's an empty vector, Its potential element is T Type of , Perform default initialization
vector< T > v2(v1)v2 contained v1 Copies of all elements
vector< T > v2=v1 Equivalent to v2(v1),v2 contains v1 Copies of all elements
vector< T > v3(n, val)v3 Contains n A repeating element , The value of each element is val
vector< T > v4(n)v4 Contains n An object that repeatedly performs value initialization
vector< T > v5{a,b,c…}v5 The element containing the number of initial values , Each element is given a corresponding initial value
vector< T > v5={a,b,c…} Equivalent to v5{a,b,c…}

It can be initialized by default vector object , This creates an empty... Of the specified type vector:

vector<string> svec; //  Default initialization ,svec It doesn't contain any elements 

** notes :** in fact , The most common way is to define an empty vector, Then when the runtime gets the values of the elements, it adds them one by one ( for example , Using member functions push_back())

List initialization vector object

​ C++11 The new standard also provides another way for vector Method of assigning initial value to element of object , namely List initialization

vector<string> svec = {"a","an","the"};

Above vector The object contains three elements : The first is a string "a", The second is the string "an", The last one is the string "the"

vector Initialization mode :

  1. Initialize with copy ( That is to use = when ), Only one initial value can be provided
  2. If you provide an in class initial value , Only copy initialization or curly bracket initialization can be used
  3. If you provide a list of initial element values , You can only initialize the list by putting the initial values in curly braces , But not in parentheses
vector<string> v1{"a","an","the"};  //  Correct list initialization 
vector<string> v2("a","an","the");  //  Wrong form 
Create a specified number of elements

​ have access to vector Object and the uniform initial value of all elements vector object

vector<int> ivec(10,1);       // 10 individual int Element of type , Each is initialized to 1
vector<string> svec(5,"CPP"); // 10 individual string Element of type , Each is initialized to "CPP"
Value initialization

​ Usually , Can only provide vector The number of elements contained in the object, omitting the initial value . At this point, the library will create a value initialized (value-initialized) Initial value of element , And assign it to all the elements in the container . This initial value is determined by vector The type of element in the object determines

vector<int> ivec(10);    //  correct ,10 Elements , Each is initialized to 0
vector<string> svec(10); //  correct ,10 Elements , Each is empty string object 
vector<int> vi = 10;     //  error , Vector capitalization must be specified in the form of direct initialization 
towards vector Object ( namely , Member functions :push_back())

​ put questions to ? How to ensure that the container space will not overflow when the length of input data is uncertain

Yes vector The object is , The direct initialization method is applicable to three cases :

  1. Known initial value and small quantity
  2. The initial value is another vector Copy of object
  3. The initial values of all elements are the same

Case study : Input 0~9 common 10 Elements , Use arrays and vector Object implementation

1. Array implementation :

#include<iostream>
using namespace std;

int num[15];

int main()
{
	for(int i=0;i<10;i++) {
		num[i]=i;
		cout<<num[i]<<ends;
	}
	cout<<endl;
	return 0;
}

2. use vector Object implementation :

#include<iostream>
#include<vector>
using namespace std;

vector<int> ivec;

int main()
{
	for(int i=0;i<10;i++) {
		ivec.push_back(i);
		cout<<ivec[i]<<ends; 
	}
	cout<<endl;
	return 0;
}

If you know the runtime, you can know vector The exact number of elements in the object , You should also use the above method to create vector Object and assign a value to it

for example :

//  Read words from standard input , Regard it as vector The element storage of the object 
string word;
vector<string> text; //  empty vector object 
while(cin>>word)
	text.push_back(word); //  hold word Add to text Back 

Key concepts :vector Objects can grow efficiently

​ C++ Standard requirements vector Should be able to add elements efficiently and quickly at run time . So since vector Objects can grow efficiently , So defining vector There is no need to set the size of the object . In fact, if you do this, the performance may be worse .

​ Start by creating an empty vector object , Add elements dynamically at run time , This practice is related to C The usage of built-in array types in languages and most other languages is different , especially C Language learners enter C++ While studying , You can expect to create vector It's best to specify the capacity of an object by the way . But in fact , Usually the opposite is true .

** notes :** If the loop contains a directed vector Object to add an element statement , You cannot use the range for loop !!!

other vector operation

​ vector Several other operations are provided

operation explain
v.empty() If v Does not contain any elements , Return to true ; Otherwise return false
v.size() return v The number of elements in
v.push_back(value) towards v Add a value of value 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 replacement of 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 == v2v1 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
<, <=, >, >= seeing the name of a thing one thinks of its function , Compare in dictionary order
vector The subscript operator for

Use vector Rules for subscript operators :

  1. Use the subscript operator to get the specified element
  2. You can't add elements in subscript form

** notes :**vector object ( as well as string object ) The subscript operator of can be used to access existing elements , It cannot be used to add elements

Tips : Subscript operations can only be performed on elements that are known to exist !

​ One thing that must be clear about subscripts : Only elements that confirm their existence can be subscripted .

for example :

vector<int> ivec;  //  empty vector object 
cout<<ivec[0];     //  error :ivec It doesn't contain any elements 

vector<int> ivec2(10); //  contain 10 An element of vector object 
cout<<ivec2[10];       //  error :ivec2 The legal index of the element is from 0 To 9

Trying to access a non-existent element in the form of a subscript will cause an error , However, this error will not be found by the compiler , Instead, it produces an unpredictable value at run time

however , This behavior of accessing non-existent elements through subscripts is very common , And there will be serious consequences . The so-called buffer overflow (buffer overflow) It refers to such mistakes , It also leads to PC And other applications on devices

An effective way to ensure that the subscript is legal is to use the range as much as possible for sentence

Case study :

​ from cin Read in a group of words and store them in a vector object , Then try to capitalize all the words . Output the changed results

#include<iostream>
#include<vector>
#include<string>
#include<cctype>
using namespace std;

vector<string> vString;

int main()
{
	string s;
	char cont = 'y'; //  Interact with users , Decide whether to continue typing 
	cout<<" Enter the first word :"<<endl;
	while(cin>>s) {
		vString.push_back(s);
		cout<<" Do you want to continue , Input (y or n)?" ;
		cin>>cont;
		if(cont != 'y' && cont != 'Y')
			break;
		cout<<" Please enter the next word :"<<endl;
	} 
	cout<<endl<<"vString String contained in :"<<endl;
	for(auto item : vString)
		cout<<item<<ends;
	cout<<endl;
	cout<<" Converted String :"<<endl; 
	for(auto &item : vString) {
		for(auto &s : item)
			s = toupper(s);
		cout<<item<<ends;
	}
	cout<<endl;
	return 0;
 } 

Iterator Introduction

Iterators are similar to pointer types , Iterators also provide indirect access to objects .

An element can be accessed using an iterator , Iterators can also be moved from one element to another .

Using Iterators

Unlike pointers , Getting iterators is not getting address characters , Types with iterators ( Such as string,vector) Members who also have return iterators

for example :

string str = "NewThreadCPP";
auto b = str.begin(),e = str.end(); // b and e Same type of 

end Members are responsible for returning to the container ( Such as string)" The next position of the tail element (one past the end)" The iterator , in other words , The iterator indicates a nonexistent... Of the container ” After the tail (off the end)" Elements

end The iterators returned by members are called tail after iterators or tail iterators .

** notes :** Under special circumstances , If the container is empty , be begin and end The same iterator is returned

Operators of standard container iterators

The operator explain
*iter Return iterator iter The reference to the indicated element
iter->men Quoting iter And get the element named men Members of , Equivalent to (*iter).men
++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 ( It's not equal ), If two iterators indicate the same element
iter1 != iter2 Or they are tail iterators of the same container , The same ; conversely , It's not equal

Generally speaking , Standard library types with iterators ( Such as string,vector) Use iterator and const_iterator To represent the type of iterator ,iterator The object is readable and writable ,const_iterator Read only

Array

An array with the vector The difference is , The size of the array remains unchanged , You can't add elements to an array at will .

Because the array size is fixed , Therefore, for some special applications, the runtime performance of the program is better , But the corresponding loss of some flexibility

notes : If you don't know the exact number of elements , Please use vector

Define and initialize built-in arrays

​ An array is a composite type , By default , The elements of the array are initialized by default

** matters needing attention :** Just like variables of built-in types , If an array of a built-in type is defined inside the function , Then the default initialization will make the array contain undefined values

Copy and assignment are not allowed

​ You cannot copy the contents of an array to another array as its initial value , You can't assign values to other arrays with arrays :

int a[] = {0,1,2};  //  contain 3 Array of integers 
int a2[] = a;       //  error ! It is not allowed to use one array to initialize another array 
a2 = a;             //  error ! You cannot assign an array directly to another array 
Standard library functions begin and end

​ C++11 The new standard introduces two new standards called begin and end Function of .

The header file :#include< iterator >

int ia[] = {0,1,2,3,4,5,6,7,8,9};
int *beg = begin(ia); //  Point to ia Pointer to the first element 
int *last = end(ia);  //  Point to arr Pointer to the next position of the tail element 
Initialize with an array vector object

​ Allows the use of arrays to initialize vector object . For this purpose , Just indicate the first element address and the last address of the area to be copied

int int_arr[] = {0,1,2,3,4,5};
// ivec Yes 6 Elements , Namely int_arr A copy of the corresponding element in 
vector<int> ivec(begin(int_arr),end(int_arr));

Suggest : Try to use standard library types instead of arrays

​ Using pointers and arrays is error prone . Part of the reason is conceptual problems : Pointers are often used for underlying operations . Therefore, it is easy to cause some errors related to cumbersome details

​ modern C++ The program should try to use vector And iterators , Avoid using built-in arrays and pointers

原网站

版权声明
本文为[Ritian juvenile wzh]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270531376090.html