[C ++ primer] chapter 16th string class and standard template library

Source: Internet
Author: User

1. string class

1) constructor

String ()

String (const char * s)

String (size_type N, char c) // All strings containing n elements are initialized to C

String (const char * s, size_type N) // initialize to the first n characters pointed to by S

Example:

#include <iostream>#include <string>using namespace std;int main(){string one("NEU Locate in shengyang");cout<<one<<endl;string two(20,'#');cout<<two<<endl;string three(one);cout<<three<<endl;string four;four=one+" realy?";cout<<four<<endl;char a[]="NEU is a famous school ";string five(a,3);cout<<five<<endl;string six(a+4,a+15);cout<<six<<endl;string seven(&a[4],&a[15]);cout<<seven<<endl; } 

2) string type input

C-style string input:

char info[100];cin>>info;cin.getline(info,100);cin.get(info,100);

C ++ style input:

string stuff;cin>>stuff;cin.getline(stuff,100);

Both versions of Getline have a common optional parameter, Getline (stuff, ';'); // end Boundary

The Getline () function of string reads characters from the input and stores them in the string until the following three conditions occur: The end of the file, the node break (\ n) maximum number of characters read

3) use string

Size_type find (string _ CH, size_type _ off = 0) const; // query _ CH from _ off and Return Index.
Size_type find (const char * _ PTR, size_type _ off = 0) const; // query _ PTR from _ off
Size_type find (const char * _ PTR, size_type _ off, size_type _ count) const; // start from _ off to find the first _ count substring of _ PTR. Is it meaningful?
Size_type find (const basic_string <chartype, traits, Allocator> & _ STR, size_type _ off = 0) const; // start from _ off to find _ Str

Example:

# Include <iostream> # include <string> using namespace STD; # define print (exp) \/* linefeed ('\') it is worth noting # It is also worth noting */{\ string: size_type Pos = exp; \ If (Pos! = String: NPOs) \ cout <# exp <"=" <POS <Endl; \ else \ cout <# exp <"= Not Found" <Endl ;\} int main () {string SS ("Hello world! _ Hello world! "); Cout <SS <Endl; print (ss. find ('O'); // directly search for oprint (ss. find ('O', 5); // search for oprint (ss. find ("he"); print (ss. find ("he", 10); print (ss. find ("Hello _"); print (ss. find ("Hello _",); // note the difference between this and print (ss. find ("Hello _", 1, 5); cout <Endl; string res ("world"); cout <res <Endl; print (ss. find (Res, 3); Return 0 ;}

4) What functions does string provide?

Auto-resize: String increases the size of existing characters, but the adjacent memory may be occupied. Allocate a new memory and copy the original content to the new memory. However, this operation is very inefficient. How does C ++ do it? Allocate a memory block larger than the actual string to increase the space of the string. If the size of the string exceeds the memory block, the program allocates a new memory that is twice the original size.

Example:

# Include <iostream >#include <string> using namespace STD; int main () {string empty; string small = "bit "; string larger = "Elephants are a gril's best friend"; cout <"Size: \ n"; cout <"\ t empty:" <empty. size () <Endl; cout <"\ t small:" <small. size () <Endl; cout <"\ t larger:" <larger. size () <Endl; cout <"capacities: \ n"; cout <"\ t empty:" <empty. capacity () <Endl; cout <"\ t small:" <small. capacity () <Endl; cout <"\ t larger:" <larger. capacity () <Endl; empty. reserve (50); // reserve allows you to request the minimum length of the memory block cout <"capacity after empty. reserve (50): "<empty. capacity () <Endl; return 0 ;}

Use C-free lab results

I don't know why it is different from the result in the book. Why ??? Wait for the answer ......


Ii. auto_ptr class

1) template class, dynamically allocate objects, and automatically clear objects when they are no longer needed

2) void remodel (string & Str)

{

String * PS = new string (STR );

STR = Ps;

Delete pS;

Return;

}

3. STL standard template library, standard template library

1) Introduction: STL is a collection of some "containers". These "containers" include list, vector, set, and map. STL is also a collection of algorithms and other components. The collection of containers and algorithms here refers to the masterpiece of many smart people in the world for many years. The purpose of STL is to standardize components so that existing components can be used without re-development. STL is now part of C ++, so no additional installation is required.

2) vector is considered a container because it can store various types of objects like a container. Simply put, vector is a dynamic array that can store any type, data can be added and compressed

Example:

# Include <iostream> # include <string> # include <vector> using namespace STD; const int num = 5; int main () {vector <int> ratings (Num ); vector <string> titles (Num); int A [num] = {2, 3, 4, 5, 6}; string B [num] = {"AA", "BB ", "cc", "DD", "ee"}; For (INT I = 0; I <num; ++ I) {ratings [I] = A [I]; titles [I] = B [I];} For (Int J = 0; j <num; ++ J) {cout <ratings [J] <"\ t" <titles [J] <Endl; // cout <ratings. at (j) <"\ t" <titles. at (j) <Endl; // another expression} return 0 ;}

3) iterator (IteratorIs an object that can be used to traverse part or all of the elements in the container of the standard template library. Each iterator object represents a specific address in the container. The iterator modifies the interface of the regular pointer. The so-called iterator is a conceptual Abstraction: What acts like the iterator can be called the iterator.

The iterator provides some basic operators: *, ++, =, and ,! =, =.

#include <iostream>#include <string>#include <vector>using namespace std;const int NUM = 5;int main(){vector<int> ratings(NUM);vector<int>::iterator pd;    pd=ratings.begin();    *pd=5;        cout<<*pd<<endl;        int a[NUM]={2,3,4,5,6};   for(int i=0;i<NUM;++i){ratings[i]=a[i];}    for(pd=ratings.begin();pd!=ratings.end();pd++){cout<<*pd<<endl;}    return 0;}

Iv. General Programming Technology

Object-Oriented programming focuses on programming data, while general programming focuses on algorithms.

General Program tools: templates and iterators

1) Why is the iterator used?

Templates make the algorithm independent from the data types stored, while the iterator makes the algorithm independent from the container type used











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.