Course record 5: programmer Interview Guide

Source: Internet
Author: User

Course record 5: programmer Interview Guide

Simultaneous sharing of Evernote: "Programmer Interview Guide" study record 5


Chapter 5 STL template and container 9th, vector container

Test site 1: Restrictions on the element types saved by containers

Voctor <noDefault> v2 (10) error. A vector <int> v1 (100) must be provided) initialize the size to 100 to avoid the constant memory allocation when the array grows dynamically. The v1.reserve (100) function is the same as above.

Test site 2: common member functions of vector

C. back () returns the last data and does not check whether the data exists. front () returns the first data c. push_back (elem) adds a data c. pop_back () Delete the last data c. reserve () retains the appropriate capacity c. at (idx) returns the data pointed to by index idx. If idx is out of bounds, the out of range

Test site 3: differentiate operations on elements accessed in a sequential container

Vector <string> svec; cout <svec [0]; The operation is incorrect because svec does not contain the element cout <svec. at (0); An out_of_range exception is thrown.

Test Site 4: delete operation

C. erase (pos) deletes the data at the pos position and returns the Location c of the next data. erase (beg, end) deletes data in the [beg, end) interval and returns the element c. erase (remove (c. begin (), c. end (), 6), c. end () delete all 6 in the container

Note: In STL, remove () only moves the object to be deleted to the end of the vector, instead of deleting the object. to delete the object, you must combine erase. However, for vector, any insert/delete operation will cause the iterator to fail. Pay attention to all continuous deletion operations. Pay attention to the delete operation. After deletion, the next data location will be returned. If you continue iter ++, a certain number will be missed.
Test site 5: shallow copy and deep copy
C ++ uses the shortest copy constructor by default.
Shallow copy: simple assignment between data members of an object. If you have designed a copy constructor that does not provide a class, when an object of this class is used to assign a value to an object, the execution process is a shortest copy.

Class A {public: A (int _ data): data (_ data) {} A () {} private: int data ;}; int main () {A a (5); A B = a; // only values between data members}

Light copy. B. data = 5 after execution
If the object does not have other resources (such as heap, file, system resources, etc.), there is no difference between deep copy and shallow copy, but when the object has these resources, for example:

Class A {public: A (int _ size): size (_ size) {data = new int [size];} // suppose there is A dynamically allocated memory () {};~ A () {delete [] data;} // release the resource private: int * data; int size;} int main () {A a (5 ); A B = a; // note this sentence}

Running will crash
Here, the pointer data of B and the Pointer a point to the same memory on the stack. When a and B analyze the structure, B first releases the dynamically allocated memory that data points, then, a parses and releases the released memory again.
The result of more than two releases of the same dynamic memory is undefined, which may cause memory leakage or program crash.
Therefore, deep copy must be used to solve this problem:
Deep copy:When a copy object is referenced by other resources (such as heap, file, and system), a new resource is opened for the object, instead of assigning values to pointers or references that reference other resources in the copy object.

Class A {public: A (int _ size): size (_ size) {data = new int [size];} // suppose there is A dynamically allocated memory () {}; A (const A & _ A): size (_. size) {data = new int [size];} // deep copy ~ A () {delete [] data;} // release the resource private: int * data; nt size;} int main () {A a (5 ); A B = a; // No problem this time}
9.2 generic programming

Test site 1: How to understand generic programming?
Generic programming is the most abstract representation programming method based on the discovery of efficient algorithms. It is mainly used to hide specific data types in function parameter calls, which can be provided to templates) only through generic pointers to call data, so as to increase reuse of functions and simplify the code.
Main features of generic programming:
1) Generic programming applications reflect STL library calls. STL is mainly composed of three parts: container, algorithm, and iterator. iterator is a bridge connecting different containers and algorithms.

2) The main operation objects of generic algorithms are different containers, but they are generally called through address transfer. The first two parameters are generally first iterator and last iterator; find (), sort (), replace (), and merge () are all generic algorithms.
3) The difference between the use of generic algorithms and the use of traditional process-oriented styles is that a function can be used more elastically to solve the same problem. The use of generic algorithm code is more concise.
Test site 2: how to change a common function to a generic function?
Common functions:

const int *find1(const int* array, int n, int x){    const int *p = array;    for(int i = 0; i < n; i++)    {        if(*p == x)        {            return p;        }        ++p;    }    return 0;}

Generic functions:

template<typename T>const T *find1(T* array, T n, T x){    const T *p = array;    for(int i = 0; i < n; i++)    {        if(*p == x)        {            return p;        }        ++p;    }    return 0;}

Method:
For container variables, you need to change the original parameters to generic pointers for transmission;
The original parameter needs to be templated for data variables, which are defined by template;
For function pointers, You need to define the function object to pass the original pointer;
For operations within a generic function, the underlying data must be avoided and replaced by pointers and function objects.

9.3 Template

Test site 1: recognition Template
The template is a tool that supports parameterized polymorphism in C ++. using the template, users can declare a general mode for classes or functions, make the parameters and return values of some data members or member functions in the class obtain any type.
There are two types of templates: function templates and class templates.
Function templates only support functions with different parameter types. Class templates are applicable to classes with different data member and member function types.
The template declaration or definition can only be performed within the global, namespace, or class scope. That is, a template cannot be declared or defined in the main function.
Test site 2: form parameters of the template
The form parameter of the template indicates an unknown type.
Template parameters: type parameters, non-type parameters, and template parameters
Type parameter: Before T, it is generallyclassOrtypename
Non-type parameters: constant values are defined within the template, that is, non-type parameters are constants within the template; non-type parameters can only be integer, pointer, and reference; A non-type template parameter must be a constant expression. The address of any local object, local variable, or local object is not a constant expression and cannot be used as a real parameter of a non-type template parameter. However, the address or reference of the global variable. The address of the global object or the reference of the const type variable is a constant expression. You can use a non-type template to form the real parameter; conversion is allowed between the form parameters and the real parameters of a non-type template.
Test site 3: Use a template to pass the pointer as a parameter to other functions

# Include <stdio. h> // comparison function int jug (int x, int y) {if (x> = 0) {return 0;} else if (y = 0) {return x;} else return x/y;} // sum function int sub (int x, int y) {return (x + y );} // evaluate the difference function int minus (int x, int y) {return (x-y);} // function pointer void test (int (* p) (int, int), int a, int B) {int Int1; Int1 = (* p) (a, B); printf ("a = % d, a = % d \ n ", a, B, Int1);} int main () {int a = 1, B = 2, c = 3, d = 4, e =-5; test (sub, a, B); // sum test (minus, c, d); // evaluate the difference test (jug, e, B ); // judge return 0 ;}

Test Site 4: Enumeration
1 ~ 9. Each number can only appear once. A 9-digit integer is required. The first digit can be divisible by 1, and the first two digits can be divisible by 2, the first three can be divisible by three ...... And so on. The first 9 digits can be divisible by 9
Code:

# Include <iostream> using namespace std; bool use [10]; // mark whether void dfs (int k, long val) {if (k = 9) is used) // 9-bit output: {cout <val <endl; return;} for (int I = 1; I <= 9; ++ I) {if (! Used [I]) {used [I] = 1; long temp = val * 10 + I; if (temp % (I + 1) = 0) dfs (I + 1, tmp); used [I] = 0 ;}} int main () {dfs (0, 0); return 0 ;}



How can I study the speech in five minutes?

Dear Chinese teacher and dear student, my speech today is titled my Chinese heart. Who never had a beautiful dream? Who never had a happy childhood? When you study in a bright classroom, do you feel happy? However, this seemingly ordinary happy life is filled with a song and a song, and has gone through the tragic history. Today, when we celebrate our motherland-our mother's birthday, please allow me to share my long-cherished Chinese heart ...... Once upon a time, our motherland experienced vicissitudes and hardships. She became a place where imperialism dumped opium and a battlefield where warlords fought in battles. She became a casino in which imperialism divided the world and where our family competed for power. She was bruised and bruised. Each inch of land is branded with deep blood marks, and each face is filled with a haze of fear. In this view, the mountains and rivers are whining, Song Tao is weeping, and China is struggling with the dark clouds. Where is the path of the motherland? What is the hope of the nation? At this moment, it is the old Chinese man who loves his birth in Sri Lanka and elders in Sri Lanka. In this critical moment of the mother's life and death, they are loyal to each other and send a sound of shock, A powerful song from the sea. They sought to fight, fold and sink the sand, bath blood battlefield, and Magu corpse ...... Lin Zexu, Hu men smoke, the fire, Wang erxiao blood sprinkling the song of sorrow, Liu Hulan Ning unyielding echo, Red Army soldiers climb the snow mountains, through the grass, swallow the mountains and rivers of the feat, the five heroes of Langya mountains earth, weeping the Spirit of God, let my Chinese children shout and rise up. Mother, how many generations of suffering, bitterness, and tears have you condensed, and how many benevolent people have hoped, beliefs, and struggles. With decades of expectation, decades of suffering, and the struggle of tens of thousands of fellow citizens, the shocking voice of Tiananmen was finally received-"the Chinese people have stood up "! I saw the Magnificent Three Gorges Dam and the golden medal in the hands of Olympic athletes. Five thousand years later, the Greater China region was established. The Great Eastern Dragon of the Chinese Nation carries the drums of the Qin Guan hanyue and the Yuan community of the Tang Dynasty, the surging poems of the goxia Lake, and the banners of reform and opening up, carrying the vision of the Chinese nation, is galloping forward at an astonishing speed! Students! Looking back on the past, we are ambitious. We have a hundred times of confidence in our prosperous years. Looking forward to the future, we are filled with pride. The vicissitudes of life have been traced, and the prosperous motherland is flourishing. When yu genwei shot at the World Cup for the first time, how could we not get involved? How can we not cheer when we hear the old samalanqi say "BEIJING" gently? How can we not be proud when Shenzhou 7 is about to enter the air and become the focus of the world again? Once the people were withered, once full of field chaos, once the sick man of East Asia, all go ...... Today, this hot land has already been overwhelming, and it's time to win. Students, teenagers are better than nations, and the people of the motherland are looking forward to us. Can we forget the responsibilities and missions entrusted by the times? Of course not. Let us take action, ignite the flame in our hearts, and strive to realize the great rejuvenation of the Chinese nation! Let's create the soul of our nation! Thank you! Patriotism should start from the side of the teacher, students: Hello everyone! Dear students, when you face the solemn five-star red flag again, do you feel passionate about your motherland? When you celebrate the annual National Day, will your mind show up in May October 1, 58 years ago. October 1, 1949 is a permanent historical day. It was the day when the People's Republic of China was formally established. On the Tiananmen floor, a five-star red flag is flying high. This is the first time that the five-star red flag has risen over 9.6 million square kilometers of vast land in the motherland. The National Flag embodies the aspirations, beliefs, and pursuits of thousands of revolutionaries, and the deep love of China's hundreds of millions of people for the motherland and the nation. Therefore, the National Day of the People's Republic of China is set to October 1 every year. The Chinese nation has a history of over five thousand years of civilization. The Chinese nation is an outstanding and great nation in the world. We had a Prosperous Tang Dynasty, a vast territory of Han Dynasty and the Yuan Dynasty, a splendid and beautiful Tang and Song culture, but also a modern history of humiliation, from the Opium War to the end of the War of Resistance against Japanese aggression. Over the past one hundred years, the imperialist powers once witnessed countless tears in the vast Chinese land. We are descendants of the Chinese People's Republic of China. We will not forget the important tasks entrusted by the nation and nations. Students... the remaining full text>

For speeches within five minutes of learning

Dear teacher and classmates:
I am very gglad to make a speech here in this class again! This time, I/'d like to talk something about English.
I love English. English language is now used everywhere in the world. It has become the most common language on Internet and for international trade. Learning English makes me confident and brings me great pleasure.
When I was seven, my mother sent me to an English school. at there, I played games and sang English songs with other children. then I discovered the beauty of the language, and began my colorful dream in the English world.
Everyday, I read English following the tapes. Sometimes, I watch English cartoons.
On the weekend, I often go to the English corner. By talking with different people there, I have made more and more friends as well as improved my oral English.
I hope I can travel around the world someday. I want to go to America to visit Washington Monument, because the president Washington is my idol. of course, I want to go to London too, because England is where English language developed. if I can ride my bike in Cambridge university, I will be very happy.
I hope I can speak English with everyone in the world. I/'ll introduce China to them, such as the Great Wall, the Forbidden City and Anshan.
I know, Rome was not built in a day. I believe that after continuous hard study, one day I can speak English very well.
If you want to be loved, you should learn to love and be... the remaining full text>
 

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.