C++__c++

Source: Internet
Author: User
Tags arithmetic bitset
1. Call the virtual function in the normal member function of the class, what is the situation? (object, reference, pointer)
Polymorphism, in fact, is the key to the Template method pattern.
2. With regard to the sequence of member variable initialization, several dependent member variables are initialized to allow the constructor to be written out.
In the initialization list, the order in which member variables are initialized is the order in which they are declared in the class, not the order in the list.
3. Write a double linked list.


Struct ListNode
{
int ndata;
listnode* Ppreviousnode;
listnode* Pnextnode;
}
The general list will have a header node and a header pointer to the table head node, should provide a listing interface, the data structure can be implemented.
4. Write a is-a and has-a.
It's easier.
Class pet{};
Class Dog:public pet{};
Class boy{pet* M_ppet;
5. struct vs. class.
1 Default Access property, struct is public, class is private


2 Default Inheritance property, struct is public, class is private
3 class can be used to declare template parameters, and struct cannot
6. The question of weighing 8 balls
No problem.
7. The implementation of vector inside the STL (application and distribution of internal space)
Vector Chinese name is a dynamic array, its internal data structure is an array, but when the array elements are not used, it is necessary to dynamically redistribute, usually twice times the size of the current, and then copy the contents of the original array of the past. Therefore, in general, its access speed is the same as a generic array, only when the redistribution occurs, its performance will decline
8. The difference between struct/class
Repeat it.
9. Why use struct
The default properties of a member are different, using struct, primarily as a collection of data.
10. How to make a class cannot be instantiated
1, constructor privatization, 2, abstract class
11. The difference between private and public inheritance.
Private inheritance: Implement only, do not inherit implementation has-a
Public inheritance: Inheritance interface and implementation is-a
Question of void *p
Cannot do pointer arithmetic operations, such as No + +
13. Differences and links between references and pointers. Whether the reference can be changed
Contact: Supports polymorphism, can be used to refer to the same object
Difference: Pointers can be null, references not allowed, pointers can be assignable, references are not available;
The basics of Windows programming, the difference between threads and processes
Program is a series of static sequence of instructions
Process is a dynamic execution of a program, the process is actually a resource container, including a private virtual address space, some initial code and data, some system resources, such as the handle
A thread is an executing body in a process, typically including a CPU register state, two stacks (kernel mode, user mode), and a TLS (thread-local Storage)
is COM + familiar?
COM + is an extension and development of COM technology that includes the basic functionality of all COM (an interface-based programming model, basic Component Services), and the combination of DCOM (which extends component technology to the distributed domain) and Mts-microsoft Transaction Server, which provides component management and configuration management on the servers side, and adds a number of services: Load balancing, memory databases, event models, queue services, etc., mainly for Windows DNA (distributed interNet Application Architecture) Three layer structure of the middle tier.
16. A brief description of the hash algorithm
The purpose of the hash table is to modify the algorithm complexity of O (1) by the query insert modification. By the key code to determine its storage address to achieve, when different key to get the same coding, it is necessary to conflict detection and processing, the general method has the remainder of the method, linear detection method, square detection method, This makes it impossible to really reach O (1)
17. A 32-bit data, how to find the leftmost 1.
If it's in the leftmost position, the number is negative, otherwise, move left one, see if it turns negative, this is an O (n) algorithm, you can also use a template to go with, and constantly change this template
O (N/2) algorithm: Two-way search ...
18. A 4*4 lattice, fill in the 1~15 and give a target status, how to search.
Like what:
1 2 3 6
0 4 5 7
8 9 10 11
12 13 14 14


And give you a final status (whatever you want).
0 represents a space, can move, a bit like a puzzle;


This is the example used in artificial intelligence textbooks, with a * algorithm, it is neither breadth search, nor depth search, but a heuristic search, in the next search, will use a valuation function to the back of the node score, take the best score for the next search, if not found results, backtracking. For the subject, using the Manhattan distance as a scoring standard is a good choice.
19. Give you 1 million data and the value of the data is sorted between 0~65535 with the fastest speed
Multi-keyword cardinality ordering msd (MOST significant DIGIT i)
20. If one of our software products, the user replied: "The speed is very slow, how do you deal with."
Ask about its workflow, the user's hardware environment
21. Eight Queen question, detailed solution (eight the Queen's question is on the 8*8 chess board, requiring a queen to be placed in each row, and can be done in the vertical direction, no conflict in the oblique direction)
Backtracking method
KMP Fast matching algorithm---it's not easy to fix.
The common pattern matching algorithm, once does not match, the pattern string moves to the right one position, but actually according to the condition, we can calculate should move several to the right to avoid unnecessary comparison; the algorithm is more tortuous
23.---Great Dijiksla algorithm for the shortest path between two points in a non-direction graph
Assuming that there are N nodes, a one-dimensional array previous[n] is required to record the previous node ordinal number, a one-dimensional array totallength[n] to record the shortest path from the origin to the current node, and a two-dimensional array weights[n][n] to record the weights of the sides between the points ( If present, then deep search or breadth search from the source point to the endpoint, as follows: When a node B is searched, the previous node is assumed to be a, and the totallength[a] + weights[a][b] is compared to totallength[b]. If less than totallength[b], then totallength[b] = Totallength[a] + weights[a][b], previous[b] = A; Conversely, no action is made. So when the search is over, the entire shortest path can be obtained from the Previous[n] array.
24. Arbitrarily give two vectors in space, to find the angle of the split line
First unit, assuming that the result is NV1, nv2, then the angle of the split line for (NV1+NV2)/2
25. What is a balance tree
The left and right subtrees are balanced trees, and ordered binary trees with a height difference of not more than 1
26. Huffman Coding problem
Rationale: Hoffman is the smallest two-fork tree with the right path length (wpl:weighted path), which is not necessarily a fully binary tree, and should be the nearest extension binary tree of the outer node with large weights. Huffman coding is the basis of data compression in order to realize the minimum redundancy code of data. It is based on the frequency of the characters appearing in the message, constructs the Hoffman tree, the left is 0, the right is 1. It has two effects, one is to ensure that the message has the shortest encoding, and the second is that the characters do not need a separator, because different characters must have a different beginning (become prefix encoding).
27. The direction diagram asks the ring
Source and end of this node? Depth first or breadth first search
28. Give n points, ask for convex package problem
A convex package (convex hull) refers to a minimum convex polygon that satisfies the n points in a polygon or within. Algorithm Description:
Find the right point as a vertex of a convex polygon (P0), traverse all other points (pi), and if the other points are on the same side of the vector p0pi, Pi is also the vertex of the convex polygon.
29. Arithmetic (to a prefix expression (polish) or suffix expression (inverse polish), then solve; give an infix expression)
+*-CDBA-/ef---------------------> a+b* (c-d)-e/f prefix-infix
operator into the stack, a variable tmp puts an intermediate operand (the result of the operation), encountered operand check whether TMP is empty, empty words take two operands, not empty words take an operand, the other is TMP, operator out stack operation, the result into TMP, if the operator, TMP empty
abcd-*+ef/----------------------> a+b* (c-d)-e/f suffix-infix
Operand stack, encountered operator, two operands stack, compute results into stack
What are the container in the STL?
Sequence container: Vector, List, deque, Bitset
Associative containers: Set, Multiset, map, Multimap
Adapter containers: Stack, queue, priority_queue
Class Container: String, Valarray, Bitset
Expansion containers: Hash_set, Hash_multiset, Hash_map, Hash_multimap
What is the way data is stored in map.
The red-black tree is a balanced binary search tree with good worst-case uptime (statistical performance is good with AVL tree)
What is the difference between map and HashMap.
The internal data structure is different, map is a red-black tree, HashMap is a hash table
is hashmap in the standard library?
No, but it's available in the SGI STL and VC2005.
The erase method in vector is different from the algorithm remove.
The vector erase is the actual deletion of the element, the iterator is not accessible. The remove in the algorithm is simply to move the removed element to the end of the container, which the iterator can access. Because algorithm through the iterator operation, do not know the internal structure of the container, so can not really delete.
What the object is.
A software construct that has an internal state, as well as an operation, used to represent a real (physical or conceptual) object.
How to prevent a class from being instantiated in C + +.
pure virtual function; privatization of constructors (friend)
37. When is the constructor normally declared private?
Singleton a single piece mode; block some actions (such as blocking copy construction)
38. When will the compiler generate the default copy constructor?
The user does not have a custom copy constructor; The copy constructor is used in the code;
39. If you have written a constructor, the compiler will also generate copy constructor.
If I write copy constructor, I won't
If I'm not writing copy constructor, same 38.
40. Why do you say that if a class is a base class, its destructor is declared virtual.
Because if you delete a pointer to a base class, if it points to an object of a subclass, then a destructor that is not virtual causes the subclass destructor to be called, causing the resource to leak. Another approach, of course, is to set the base class destructor to protected.
What is the difference between a inline function and a #define? When will really be inline, when not?
1 macros are in the precompiled phase of simple text substitution, inline in the compile phase to implement the expansion
2 macros will definitely be replaced, and complex inline functions will not be expanded
3 Macro error (Order of operation), and difficult to be debugged, inline will not
4 macros are not type-safe, and inline are type-safe, providing type checking for parameters and return values
Inline fails when the following conditions occur
function size is too large
Inline virtual function
There is a loop or recursion in a function
function calls other inline functions
42. What does it mean to write the member functions of a class in the declaration of a class?
Inline this function (inline is similar to template and must be implemented in. h)
There is an architectural distinction between public inheritance and private inheritance.
Public is the is-a relationship, the inheritance interface and the implementation
Private is a has-a relationship that inherits only the implementation
44. In multiple inheritance, if a class inheritance inherits both Class A and Class B, and Class A and B have a function called foo (), how to explicitly indicate in the subclass which parent class Foo () is override.
First of all, Foo in a,b should always be virtual function, otherwise directly covered, there is no this problem, secondly, the problem from a grammatical point of view seems to be unresolved. Because we can not change the original design (otherwise there is no problem:), all had to be considered from the Extend:
Class Ea:public class A
{
Public
virtual void foo () {Fooa ();}
Private
virtual void Fooa () = 0;
}

Class Eb:public class B
{
Public
virtual void foo () {Foob ();}
Private
virtual void Foob () = 0;
}

In this way, I can override different functions to achieve this goal.
Class Ab:public EA, pubic EB
{
Private
virtual void Fooa () {}
virtual void Foob () {}
}
45. What is the syntax of virtual inheritance?
A
/     \
B C
\ /
D
Class a{};
Class B:virtual public a{};
Class C:virtual public a{};
Class D:public B, public c{};
46. Partial template special case and all template special case is what difference.
The bias is only used in class templates, while the full specificity applies to function templates, class templates.
The result of the partial specificity is still a template, and the result of the total specificity is a specific type.
47. Make a function to transpose a single linked list.
It should be in reverse order.
This small algorithm actually took me a lot of time, not tested:
struct ListNode
{
int data;
Listnode* Next;
};


void Reverselist (listnode* p)
{
listnode* p0 = NULL;
listnode* P1 = p->next;
listnode* P2 = p1? p1->next:null;


Three pointers, representing the current processing node, the previous node and the latter node, respectively
To save a node by reusing the head node next
while (NULL!= p2)
{
P->next = p2->next; Temporary storage


P1->next = P0; Reverse
P2->next = p1;


P0 = p1; One node down
P1 = p2;
P2 = p->next;
}
P->next = p1; P1 the end element into the first element, the chain head node
}

48. Split an integer, such as 4, can be disassembled into 4=3+1;4=2+2;4=2+1+1;4=1+1+1+1
First, after splitting a number, you may have to split the last factor, so use recursion; second, the n+1 factor is less than or equal to the nth factor; Furthermore, for the last factor, I can output directly or continue splitting.
The algorithm is as follows:

void print (int res[], int num)
{
for (int i = 0; i < num; ++i)
{
printf ("%d", res[i]);
}
printf ("\ n");
}
N represents total, m represents maximum factor
void Split (int n, int m)
{
static int res[100]; Save Results
static int num =-1; Current factor subscript
num++;
Recursive termination conditions, 0 can not be divided, direct output
if (0 = n)
{
Print (res, num+1);
num--;
Return
}
Else
{
if (n = = m)
{
Do not disassemble, direct output
Res[num] = m;
Print (res,num+1);
num--;
}
Else
{
Split the first
Res[num] = m;
n = n-m;
Maximum factor cannot be greater than total
if (m>n) m = n;


Loop, the second factor can continue splitting and can be split into multiple
for (int i = m; i>=1;-I.)
{
Split (n, i);
}
num--;
}
}
}


void Split (int n)
{
for (int i = n-1; i>=1; i--)
{
Split (n, i);
}
}


Alas, old, this little thing has been doing me for a long time ....
49. Do not use the library function, realize strcpy or memcpy function
Byte-by-byte copy of the past, but consider the source memory and target memory overlap.
50. Function and disadvantage of inline function
Insert the code directly into the call place, can reduce the number of function calls, but it will increase the size of the code, and if the inline failure, in each call obj, will produce a copy of the function, so that there is no way to reduce the size of the code, without reducing the function of the call, lend your money ...
51. The difference between pointers and references
The pointer can not initialize, the reference must be initialized
The pointer can be null, and the reference must refer to a real object
Pointers can be redirected to other objects, and once the references are initialized, they are no longer changed
52. The meaning of Friends
Enables a function or class declared as a friend to access a class's non-shared members.
53. The meaning of virtual function
Realizing polymorphism
Overload, Overwrite, Override and their respective characteristics and significance
Overload: Function overload (same name, different parameter)
Overwrite: Covering
Override: virtual function overload
55. What is the Ifndef/define/endif in the header file?
Prevents the header file from being repeatedly referenced.
What is the difference between #i nclude <filename.h> and #i nclude "Filename.h"?
#i nclude <filename.h&gt: From the standard library path to find the file, for VC, should also include the VC environment settings options included in the directory and engineering properties specified in the directory
#i nclude "filename.h": first in the current directory lookup, if not found, in the way above to find
57. In C + + programs to invoke the compiler compiled by the C compiler function, why add extern "C".
The C + + language supports function overloading, which does not support function overloading. A function is compiled in C + + and the name in the library is different from the C language. C + + has provided a connection exchange specified symbol extern "C" to solve the name matching problem
58. A class has a base class, a member object with another class inside it, and the execution order of the constructors.
Executes the base class first (if there are virtual base classes in the base class, the other base classes execute the virtual base class first, followed by the order in which the derived class is declared), and then the member object is executed.
59. Please describe a design pattern that you are familiar with
This looks familiar to you. Singleton the simplest, template method with the most, bridge is very cool, command blow Undo,redo also good ...
60. In UML, what is the difference between aggregation (aggregation) and composition (composition).
In fact, from the name can be separated out.
Aggregation representation is simply aggregation, there is no essential connection, so the survival time of these objects is not related;
The combination represents a closer relationship that has a common lifetime.
A typical example is the Monkey King, the arm, the divine relationship ....
C # and C + + are different in addition to the grammatical differences.
C + + is the direct generation of executable code, while C # is the middle code, until the first execution, the JIT (Just in time) to generate executable machine code.
And there is (1) C # has garbage automatic recycling mechanism, programmers do not worry about the object of recycling. (2) C # Strictly prohibit the use of pointers, can only handle objects. If you want to use pointers, you can use pointers only in unsafe blocks. (3) C # can only be inherited by single. (4) Static members must be accessed through the class name. You cannot access static members through objects, as in C + +. (5) When overriding a virtual function of a parent class in a subclass, it must be override with the keyword, and the method of overriding the parent class is to use the key word new
The difference between New delete and malloc free
For classes, New and delete invoke the constructor, the destructor
New,delete can be perceived to be of type. New returns a defined type, delete deletes a specified type so that no size is given. and malloc and free are both dealing with void types. You must be forced to type conversions at all times.
#define DOUBLE (x) x+x,i = 5*double; I is how much. What the right statement is.
I = 5*10+10 = 60 60
The correct statement is:
#define DOUBLE (x) ((x) + (x))
64. What kinds of situations can only use intialization list and not use assignment?
When a class contains a const, reference member variable; A constructor for a base class requires arguments; A class contains member objects of other classes, and the constructor of that class requires arguments.
C + + is not type-safe.
No. Two different types of pointers can be cast. C # is type-safe.
What code is executed before the main function executes.
The constructor for the global object executes before the main function.
67. Describe how memory is allocated and how they differ.
(1) Distribution from the static storage area. The memory is allocated when the program is compiled, and exists throughout the running of the program. such as global variables, static variables.
(2) created on the stack. When the function is executed, the storage units of local variables within the function can be created on the stack, and the storage units are automatically freed when the function is finished. The stack memory allocation operation is placed within the processor's instruction set. With cache, faster but less capacity.
(3) Allocation from the heap, also known as dynamic memory allocation. The program uses malloc or new to request any amount of memory at run time, and the programmer is responsible for releasing the memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most.
(4) The literal constant area, such as char* p = "Hello, world" is an example, and its memory is already allocated when the program is compiled.
A program in addition to these, there is a (5) program code area.


68. Compare the differences between static_cast and dynamic_cast in C + +.
Static_cast can explicitly do some automatic conversion, such as some int, char some basic type of conversion, and the conversion between pointers. But it does not guarantee security. The main function of dynamic_cast is to convert a base class pointer into a subclass pointer, because the base class pointer does not necessarily point to the object of the type we want to convert, so the conversion can fail, dynamic_cast can know the failure and return null, and STATIC_ Cast is not so clever, because dynamic_cast will use Rtti to find out whether the conversion is feasible. (more time consuming.) )
69. When there is no life in a Class A member variable and member function, then the value of sizeof (a) is how much, if not 0, please explain why the compiler did not let it zero.
Not zero, different objects should have different addresses, suppose I declare an array of a a[2], if it is zero, then the address of a[0] and a[1] is not the same
70. It is known that two lists of Head1 and head2 are in order, please merge them into a linked list which is still in order and requires recursive method.
Merge sort, should be relatively simple. Note that if a linked list is empty, then you can simply link the other directly to the past.
Baidu Written Question:

#include <iostream>


using namespace Std;


int foo (int a)
{
int x, y, Z;
x = a/100; Hundred
y = (a-x*100)/10; Ten
z = a-x*100-y*10; Bit


cout << a << "" << x << "" << y << "" << z << "" << a+x +y+z << "\ n";


return a+x+y+z;
}


int main ()
{
cout << "Wait for output:\n";
for (int i = 1; i < 1000; i++)
{
Int J = (i-27) > 0? (i-27): 1;
for (; J < I; J + +)
{

if (i = = foo (j))
{
Break
}
}


if (j = = i)
{
cout << i << "\ n";
}
}
return 0;
}



#include <iostream>


using namespace Std;


const int max_arr=100;


int * Compare (int a[], int size_a, int b[], int size_b)
{
int *result = new Int[max_arr];
int i = 0, j = 0, k = 0;
while (I < size_a && J < Size_b)
{
if (A[i] > B[j])
{
j + +;
}
else if (A[i] < b[j])
{
i++;
}
Else
{
result[k++] = A[i];
i++; j + +;
}
}

Result[k] = 0;
return result;

}


int main ()
{
int a[10] = {5, 12, 25, 31, 42, 45, 64, 65, 84, 98};
int b[15] = {12, 42, 46, 65, 67, 81, 86, 88, 89, 96, 98, 102, 123, 145, 485};


int *arr = Compare (A, ten, B, 15);
for (int i = 0; i < Max_arr && Arr[i]!= 0; i++)
{
cout << Arr[i] << "";

}


return 0;
}









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.