c ++ simple finishing face questions

 

About the interview, most of the jobs I voted for image processing-related, which involves a lot of knowledge of C ++, which is some time ago summary of C ++ interview questions often, mostly from cattle passenger networks and various blog, in my the actual interview appeared in the issue has been highlighted expressed.

The difference between 1 C and C ++?

1) C ++ language is object-oriented, and C is the process-oriented programming language structure

2) C ++ with encapsulation, inheritance and polymorphism three properties

3) C ++ supports programming paradigms, such as the template class, function templates

2 C ++ pointers and references the difference?

1) a pointer has its own space, but cited just an alias;

2) may be initialized to a null pointer, and reference must be initialized to be a reference to an existing object;

3) pointer to an object referred to may change in use, when the initialization is fixed, and can not be changed by reference;

4) pointer points to the next object is represented by +, ++ means referents reference plus 1.

3 smart pointer

Inside the four C ++ smart pointer: auto_ptr, shared_ptr, weak_ptr, unique_ptr wherein the three support is c ++ 11, 11 and the first has been abandoned.

Why use a smart pointer:

The role of smart pointer is a pointer management, because there is such a case: space applications forget to release at the end of the function, resulting in a memory leak. Use smart pointers can largely avoid this problem, because the smart pointer is a class when the class is beyond the scope of that class will automatically call the destructor, the destructor will automatically release resources.

4 The main difference between pointers and arrays

1) is stored in the data array, the data stored in the address pointer

2) direct access to the array data, and pointers to access the data, the content of the pointer is first obtained, and then as an address data from the address extracting

5 Why destructor must be virtual? Why default C ++ destructor not virtual

1) The destructor may be inherited parent class is set to the virtual function, ensures that when we new subclass, then the base class pointer to the subclass object, release a base pointer can be freed subclass space, prevent memory leaks.

2) C ++ destructor default virtual function is not needed because the additional virtual function tables and virtual virtual function table pointer, additional memory. For not inherited class, its destructor If a virtual function, memory is wasted. Thus the default C ++ destructor not virtual, but only when it is necessary as a parent class virtual function set.

Function pointer 6

First, the function pointer is itself a pointer variable, the variable is a pointer pointing to a specific function. As this pointer may point to the variable integer variable, the same character array, this is pointing function.

C at compile time, each entry has an address of a function, the entry address is the function pointer points to the address. With the function pointer variable, calls the function pointer variable which can be used, just as with other types of pointer variables can reference variable, in that these concepts are substantially uniform. (The function may be passed as parameters, you can achieve polymorphism: a pointer to a different function)

7 C ++ destructor in

1) destructor the corresponding constructor, when the object end of their life cycle, as a function of where the object is invoked, the system will automatically execute the destructor;

2) The destructor name should be the same as the class name, just add a bit inversion function name in the symbol ~, ~ e.g. Stud (), to distinguish it from the constructor. It can not take any parameters, no return value (void type including). Only one destructor, can not be overloaded.

3) If the user does not write destructor, the compiler will automatically generate a default destructor, if a class has a pointer, and during use in a dynamic application memory, it is preferable to display the destructor before the destruction of the class, freed memory space application, to avoid memory leaks.

4) class destructor sequence: 1) itself derived class destructor; 2) destructor object member; 3) base class destructor.

8 overloading and cover

Overload: two functions the same name, but different parameter list (number, type), the type of the return value is not required, in the same scope

Rewriting: subclass inherits the parent class is the parent class virtual function in the subclass redefines the virtual function, this situation is rewritable

9 static keyword

1) added a global variable static keyword can only be used in this document. Ac is defined in the example in static int a = 10; int a then not get used in a variety of extern bc, a scope only in ac.

2) static local variables defined statically allocated data segment, Common local variables allocated on the stack, because of the release function stack frame is released.

3) For a class member variables and member functions, plus the static keyword, this variable / function, there is no this pointer, and must pass the class name to access

10 polymorphism and virtual functions

Multi-state is divided into static and dynamic multi-state multi-state, multi-state mainly static overloaded, it has been determined at compile time; dynamic polymorphism is implemented with virtual functions mechanism, dynamic binding at runtime. For example: a type of the parent class pointer to a subclass object when a pointer used to call the parent class subclasses the overridden virtual function of the parent class when the child class function calls after rewriting, in the parent class is declared as a function of the addition of the virtual keyword, rewriting time also you do not need to add virtual virtual function in a subclass.

11 ++ i and i ++ implementations

++ i to increment 1, then return, i ++ first returns i, then incremented by one

1) ++ i realized:

int&  int::operator++() { *this +=1; return *this; }

2) i ++ implementation:

const int  int::operator(int)

{

int oldValue = *this;

++(*this);

return oldValue;

}

12 C ++ function maximum stack space

The default is 1M, but you can adjust

13 What is the difference between new / delete and malloc / free is

1) new / delete are C ++ keywords, and malloc / free is a C language library functions

2) the use of the latter must indicate the size of the memory space of the application, the type of the object class, which does not call the constructor and destructor

14 C language sequential pushing of the parameters

From right to left                              

15 map and set any difference

1) associated with the container and the map are set in C ++, the underlying implementation is black trees (RB-Tree).

2) map elements are in key-value (key - value): functions index key, the index value is associated with the data representation; the Set contrast is simply a collection of keywords, each SET element contains only one keyword.

Iterator 3) set the const is not allowed to modify the value of the element; Map allows modification value, but not modify key.

4) map supports the subscript operator, set does not support subscripting. map can be done with the index key,

16 difference between vector and list of

1) vector, the continuous storage container, dynamic array, the space allocated on the heap;

The underlying implementation: Array.

If there is no space left, the space will be reconfigured twice the original number of elements, then the original spatial elements to initialize a new space by way of replication, again increasing the elements of the new space.

Applicable scene: frequent random access, and do not often non-tail node insertion and deletion.

2) list, dynamic list, allocated on the heap space, each insert a metadata will be allocated space, each element will be deleted to free up space.

Bottom: a doubly linked list

Access: random access performance is poor, only to quickly access the beginning and end nodes.

Applicable scene: often insert delete large amounts of data

2) vector for insertion and deletion in the intermediate node causes memory copy, list not.

3) vector good-time allocation of memory, enough only 2-fold expansion; list each time you insert a new node will be memory applications.

4) vector has a contiguous memory space, support random access, if the need for efficient access immediately, but not with the insertion and deletion of efficiency, the use of vector.

list does not have a period of continuous memory space, if you need an efficient insertions and deletions, not on random access, you should use the list.

17 STL iterators in effect, why should there pointer iterators

1) Iterator (Iterator) mode, also known as the Cursor (cursor) mode, for providing a sequential access method for each element a polymeric object, without exposing the interior of the object representation.

2) iterator is not a pointer, a class template, acting like pointer. He just mimics some of the function pointer by overloading some operators pointer, ->, *, +, -, etc., equivalent to an intelligent pointers.

3) iterator causes:

Iterator class way to access the different collections of abstracts access logic, such structures do not expose the inner set to achieve the effect of the loop through the collection.

18 STL iterator is how to remove elements of it

1) For the container series vector, deque, the post-use erase (itertor), each element behind the iterator will fail, but behind each element will move forward one position, but will return the next valid erase iteration device;

After 2) associated with the container map set, using the erase (iterator), the current element of the iterator fails, but the structure is a red-black tree, to delete the current element does not affect the iterator to the next element, so before calling erase, record iterator to the next element.

3) For the list, it is not continuous use of the memory allocation, and its erase method also returns a valid next Iterator,

19 access to the C ++ class members

C ++ to control access to the member variables and member functions through public, protected, private three keywords, which represent the public, protected, private, known as a member access modifier. Within the class (defined inside the class code), both members were declared as public, protected or private, are accessible to each other, there is no access restrictions. In (outside the defined class code) outside the class, and can only be accessed by members of the public properties access the object through the object member, and can not access the private, members of the protected property.

20 difference between struct and class in C ++ of

In C ++, you can use struct and class definitions class can inherit. The difference is: the default permissions inheritance and default access struct is public, and the class of default and default access permissions inheritance is private.

21 left and right values

1) Left value: to take the address of an expression, or named object / variable. Generally refers to persistent objects still exist after the end of the expression.

Right value: You can not take the address, or an anonymous object of expression. Generally refers to the end of the temporary object is an expression that no longer exists.

2) the address value can be left, and the right value is not. Value can be assigned left and right values ​​can not be assigned, can be used to assign values ​​to the left. Value of the variable left and right immutable values.

What are the new features 22 C ++ 11 has

1) auto Keywords: compiler can automatically deduce the type of the initial value. But not in the reference and array type transfer function derived

2) nullptr Keywords: nullptr is a special type of literals, it can be converted into any other type of pointer; and NULL is generally defined as macro 0, problems may occur in the event of overloading.

3) smart pointers: C ++ 11 added a std :: shared_ptr, std :: weak_ptr and other types of smart pointers, to solve the problem of memory management.

Process 23 C ++ source files from the experience of text into an executable file

1) pre-processing stage: the source code file containing the file relationship (header), prepared statement (macros) and analyzed Alternatively, pre-compiled file generation.

2) compile stage: converting the pre-compiled into a specific file preprocessed assembly code to generate the assembler file

3) the compilation phase: phase conversion compiled into machine code generated assembler file, generate relocatable object files

4) Link stage: multiple object files and libraries required to connect into a final executable object file

24 include the order header file and double quotation marks "", and angle brackets <> distinction

1) the difference between the angle brackets and double quotes: compiler pre-processing stage to find the path to the file header is not the same.

2) The header file contains a double quotation marks, to find a header file path order, first find the current directory header

24- C ++ memory management is how

1) code segment: a read-only memory area and a text area, wherein the read-only storage area storing the machine code string constants, storing the program text area.

2) data segments: storage program initialized global and static variables

3) bss group: storage uninitialized global and static variables (global + local), and all variables are initialized to 0 and the global static variable.

In the dynamic allocation of memory heap, and you need to call delete when you call new / malloc function / free to manually release the application memory: 4) heap.

5) Stack: Returns the stack address space stored functions, parameters, local variables, return values

25 memory leaks, mistakes

1) calls a memory leak is usually due to the operation of malloc / new application memory and the like, but the lack of a corresponding free / delete. Determine whether the memory leak: Memory leak checking tool Valgrind in 1 linux environment, you can add 2 memory allocation and release of statistics when writing code, whether the current application and release of statistics consistent memory.

2) segment error usually occurs when accessing illegal memory address, specifically divided into the following situations:

The use of wild pointers

Attempts to modify the contents of the string constant

26 difference between the new and malloc

1, new allocated memory is allocated according to the data type, malloc allocated memory size specified by the allocation;

2, new returns a pointer to the specified object, and malloc returns void *, so the return value of malloc generally required conversion type.

3, new not only allocate a section of memory and will call the constructor, malloc will not.

4, use the delete destruction of memory allocated with new, malloc free to use to destroy; when a delete calls the destructor of the object, but is not free.

5, new is an operator can be overloaded, malloc is a library function.

27 Software Development Process

1) Demand Analysis

2) outline design

3) Detailed Design

4) coding

5) Test

6) software delivery, acceptance

7) Maintenance

28 c / s and b / s architecture

1) C / S architecture is the first software architecture earlier, is mainly used for LAN. Also known as the client / server model

Client and server is divided into two tiers:

First layer: on the client system display screen in conjunction with the business logic;

Second layer: the network in conjunction with a database server.

If the user needs to use it to download a client, after installation can be used, such as QQ, micro-letters.

Advantages: 1) C / S architecture and interface operations may be very rich. 2) safety performance can be easily ensured. 3) Since only one layer interacting, so response speed.

Disadvantages: 1) fixed users. Because the program needs to be installed before use, and therefore not suitable for the unknown number of users. 2) high maintenance costs, the occurrence of an upgrade, all client programs need to be changed.

2) B / S architecture called the Browser / Server, i.e. the browser / server architecture.

B / S architecture has three layers, namely:

The first layer presentation layer: the background and allows user interaction and the final results of the query output.

The second layer logical layer: mainly used to complete the server application logic client functionality.

Data layer The third layer: mainly subject to independent operation after various client requests.

Advantages: 1) the client without having to install, have a Web browser. 2) BS architecture can be placed directly over the WAN, interactive. 3) BS architecture eliminates the need to upgrade multiple clients, you can upgrade the server.

Cons: 1) in terms of speed and security need to spend a significant design cost, which is the biggest problem BS architecture. 2) the client server interaction is a request - response pattern, usually need to refresh the page.

3) C / S and B / S have their own advantages, C / S on the performance capabilities of the graphics and speed running is definitely stronger than the B / S mode, but the drawback is that he needs to run a special client, and more it is important that it can not be cross-platform

29 database transactions

Transaction (Transaction) system is a series of data for access to a program update operation consisting execution logic. DBMS transaction is the most basic unit, indivisible transaction.

Transaction has four basic characteristics, namely: Atomicity (Atomicity), consistency (Consistency), isolation (Isolation), persistent (the Duration), referred to as ACID.

1) Atomic: A transaction is considered indivisible minimum unit, all things to be unsuccessful operation, or failure rollback.

2) Consistency: database before and after the transaction execution are consistent state.

3) Isolation: a firm to make changes before final submission, other transactions are missing

4) Durability: Once a transaction commits, modify it done will always be saved to the database

30 Database Index

Database queries in order to increase the index table speed of identifying a field added, the value is a structure of a database table in one or more columns to sort.

DB in the implementation of a Sql statement, the default mode is a full table scan based on search criteria, the matching conditions encountered Join the search result set. If we add a field by the index, the index list will go a query to locate specific number of rows value, greatly reducing the number of lines traverse the match, it can significantly increase the speed of queries.

advantage:

1) by creating a unique index, you can guarantee the uniqueness of each row of data in a database table.

2) can greatly accelerate the speed of data retrieval, which is the main reason the index was created.

Disadvantages:

1) index needs to occupy physical space

2) When the data in the table to add, delete and modify, the index should be dynamic maintenance

Three Forms 31 Database

1) The first paradigm: When all the attributes of the relational schema R can no longer broken down into more basic data unit, said first normal form is R, i.e., attributes can not be separated

2) The second paradigm: If R satisfies a first relational schema paradigm, and all non-primary property of R are totally dependent on each of the candidate key attribute of R.

3) Third Pattern: i.e. non-primary property is not dependent on the key code transmitted

31 SQL Optimization What

1) optimize queries by indexing

2) the query optimization, should try to avoid full table scan

32 balanced binary tree (AVL trees) and red-black tree

1), also known as an AVL tree balanced binary tree is a special binary sort tree. Left and right subtrees are balanced binary tree, and the absolute value of the difference between the left and right subtrees height of not more than 1.

2) a red-black tree is a binary search tree, but adds a bit stored at each node of the node represented by the color may be black or red (i.e. red non-black), red-black tree is a balanced binary tree weak, relatively under a demanding AVL tree, the small number of its rotation, so the search, insert, delete many cases, usually red-black tree.

3) so that the red-black tree search, insertion and deletion performance is O (logn), and stable performance, so there are many structures comprising STL map are used to achieve the underlying red-black tree.

Huffman coding 33

Huffman Coding Huffman tree is an application widely used in the data file compression. Huffman encoding algorithm with the frequency of characters that appear in the file to establish the optimal use of 0,1 represents the character representation.

34 map and the underlying implementation unordered_map

red-black tree map is based on the underlying implementation, therefore map the internal arrangement of elements is ordered. And unordered_map hash table is based on the underlying implementation, so the order of its elements is disorderly.

35 reasons for stack overflow

Stack overflow refers to a program exceeds the number of bytes of the variable itself to apply a variable number of bytes of stack written.

1) local array is too large. When the internal function of the array is too large, it may cause a stack overflow, local variables are stored in stack.

2) Too many recursive call hierarchy.

3) a pointer or array bounds. For example, string copy, or processing a user input and the like.

36 difference between stack and heap

C language memory model is divided into five zones: Zone stack, heap, static area, constant area code area.

1) Stack Area: storing the function parameters, local variables, etc., is automatically allocated and freed by the compiler. Stack is automatically assigned by the system, high speed, but the programmer can not control.

2) heap: through memory block new, malloc, realloc assignment, the compiler will not be responsible for their release work. General distribution release by the programmer, not the release may cause a memory leak. The heap is allocated its own programmers, slow, prone to debris, but easy to use them.

3) global variables and static variables are stored on a piece of.

4) Constant area: constants stored here can not be modified.

5) Area Code: storing binary code function body.

37 arrays and lists

1) a continuous array element is stored in memory, a high efficiency is the same as a random access memory for each element, quick access to index by any element in the array, so the array. Low insertion and deletion of data efficiency data array.

An array of random access and strong, fast search speed, low insertion deleted efficiency, there must be contiguous memory space.

2) the list of elements in memory is not stored sequentially, but are linked by a pointer to the elements together, the list increased remove elements very simple, just change the pointer element on the line. Insert delete speed, high memory utilization, memory is not wasted, not a random search.

38 quick sort in C ++

nt once_quick_sort(vector<int> &data, int left, int right)

{

int key = data[left];

while (left < right)

{

while (left < right && key <= data[right])

{

right--;

}

if (left < right)

{

data[left++] = data[right];

}

while (left < right && key > data[left])

{

left++;

}

if (left < right)

{

data[right--] = data[left];

}

}

data[left] = key;

return left;

}

int quick_sort(vector<int> & data, int left, int right)

{

if (left >= right )

{

return 1;

}

int middle = 0;

middle = once_quick_sort(data, left, right);

quick_sort(data, left, middle-1);

quick_sort(data, middle + 1, right);

}

39 hash table (hash table)

Implement hash table includes construction and processing of hash collision Hash: Hash structure, including direct address method, stay in addition.

Processing hash collision: when the hash table is large set of keywords, different key value element may be mapped to the same address hash table, such a phenomenon is called hash collision. Common solutions include:

1) Open addressing method, when the conflict in some way to continue probing for other storage units in the hash table until you find an empty position so far. (E.g., linear probing, the probe squared)

2) re-hashing: When a collision occurs, the address value calculated by another hash function, until the conflict no longer occurs.

3) Chain address method: all the same key hash value chain storage, key is inserted into the list in order.

40 merge two ordered lists

class Solution {

public:

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

if(l1 == NULL)

{

return l2;

}

if(l2 == NULL)

{

return l1;

}

if(l1->val < l2->val)

{

l1->next=mergeTwoLists(l1->next,l2);

return l1;

}

else

{

l2->next=mergeTwoLists(l1,l2->next);

return l2;

}    }     };

Reverse pointer 41

/*

struct ListNode {

    int val;

    struct ListNode *next;

  

};*/

class Solution {

public:

    ListNode* ReverseList(ListNode* pHead)

    {

        // reversed pointer

        ListNode * pNode = pHead; // current node

        ListNode * pPrev = nullptr; // a node of the current node

        ListNode * pNext = nullptr; // current node to the next node

        ListNode * pReverseHead = nullptr; // pointer to the new head of the linked list

        // reverse list

        while(pNode!=nullptr)

        {

            pNext = pNode-> next; // establish links      

            if (pNext == NULL) // determines whether the last node pNode

                pReverseHead = pNode;

            pNode-> next = pPrev; // pointer reversal

            pPrev=pNode;

            pNode=pNext;

        }

        return pReverseHead;

    }

};

42 C ++ in the const keyword

1) const variables can be modified, reference, pointer, etc., when the pointer is modified, the * indicates the left pointer data is constant, unchangeable, but the pointer can point to other memory cells. * When the right indicates the pointer itself is a constant, can not point to other memory address, but the data pointer may be changed.

2) const argument function may be modified, the parameters passed to it can not be changed within the function. Can be modified member variable, the variable becomes constant, it can only be read not write.

3) const member functions and modify function when the const after the function name, it modifies the member function can not modify any of the member variables, const member functions can not call any non-const member functions.

4) const objects can be modified, const object can only call const member functions, it is necessary to provide a version of const member functions.

43 role in the static keyword in C ++

1) The most important one: Hide

When compiling multiple files at the same time, not all of the prefix plus static global variables and functions have global visibility. If the front of the variables and functions added static, then it will hide other source files. Using this feature, you can define functions and variables of the same name in different files, without worrying about naming conflicts.

2) The second effect is persistent (static variables remain variable content in the global memory function and life cycle)

Static data stored in the variable region will be completed initialization program started running, and only time initialization. Furthermore, if the local variable is defined as static within the function, it is the whole life cycle of the source, but the scope of the same automatic variable. Use only the static variable in the function. After exiting the function, despite variables still exist, but you can not use it.

3) The third effect of the static default initialized to 0 (static variable)

4) The fourth action: c ++ class member declarations in the static

When static class declared variable or function, using the initialization scope operator to indicate the class to which it belongs.

Static member function of a class 1 belongs to the entire class rather than an object, so it does not have this pointer. 2 can not be static member function is defined as virtual. 3 static data members are static storage, so it must be initialized.     

44 C ++ and the new malloc

1) New and malloc are on the heap memory of the application. Malloc and free are library functions, c / c ++ can be used, new and delete are c ++ keywords.

2) New can call the constructor of the object, delete the corresponding call the destructor. Malloc allocate memory only, free

Only free memory.

3) the underlying new / delete calls the malloc / free.

4) c ++ allows overloading new / delete operator, malloc allowed overload.

5) char *p; p=(char*)malloc(100)。int *p=new int; int *a = new int[100];

6) new returns a pointer to an object type, such as the above p, returns a pointer to int. And malloc returns * void, i.e. untyped pointer needs to be done cast.

 

 

                                 

Guess you like

Origin www.cnblogs.com/libai123456/p/12099235.html