杂记

1. 静态链表第一个元素value为任意值, next为1

2.Copy&Assignment constructor 3法:

   default,在public里实现,在private里实现(不是所有的都能实现)

3. Multidimensional Vector

vector< vector<int> > vec(4, vector<int>(4));

4.原码,反码,补码
  正数:原反补都一样
  负数:反码->符号位不变,其他位取反
        补码->反码+1
  已知补码求原码: 取反加1(和原码求补码一样)
  
	取值范围:-2^N~~~~2^N-1 负数之所以多一个是因为(100000000)为最大负数,即-2^N
 
2进制转10进制: 整数位*2,小数位除2
10进制转2进制: 整数位除2,取余, 小数位乘二,取整。

5.  function pointer 和 typedef 结合用法

class GameCharacter;                               // forward declaration



// function for the default health calculation algorithm

int defaultHealthCalc(const GameCharacter& gc);



class GameCharacter {

public:

  typedef int (*HealthCalcFunc)(const GameCharacter&);



  explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)

  : healthFunc(hcf)

  {}



  int healthValue() const

  { return healthFunc(*this); }



  ...



private:

  HealthCalcFunc healthFunc;

};

6. Composition & Aggregation

Compositions:

  • Typically use normal member variables
  • Can use pointer values if the composition class automatically handles allocation/deallocation
  • Responsible for creation/destruction of subclasses

Aggregations:

  • Typically use pointer variables that point to an object that lives outside the scope of the aggregate class
  • Can use reference values that point to an object that lives outside the scope of the aggregate class
  • Not responsible for creating/destroying subclasses

7. Recursion VS Iteration

In most (but certainly not all) situations, iteration is faster than recursion

I was able to find two good reasons to consider recursion over iteration.

  1. The code can be clearer and simpler
  2. Recursion offers more elegant solutions

8. 把STL container(vector, stack)传给函数时,如果想改变里头的值,必须要用reference

9. 用exit可以结束程序,可用于结束需要返回值的程序。

10. 指针只有当用new创建时才在heap上,否则都在stack上,不需要用delete来删除。
11. Vector中不能装reference,但是能装指针。
12. 当函数返回值是指针时,不能返回指向本地变量的指针,必须要new一个指针。例如
string * test()
{
string *aa = new string("test");
return aa;
时刻记住,local的指针要想传回给别的地方,必须要new。


13. sort中若自定义compare函数,必须要写成全局函数,不能写成类的成员函数,或者可以用lambda表达式, 定义匿名函数

sort//可以用lambda表达式, 定义匿名函数, 语法是  [] (参数表){ 实现 } 匿名函数会自动成为友元
(nodeList.begin(), nodeList.end(), [](Node* node1, Node* node2)
{
return(node1->getDist() < node2->getDist());
}
);


14. c++中开辟空间大小 int * aa = new int[]

注意此处使用【】而不是(),【】是开辟大小,()只是创建一个指针。


15. List 和 vector的区别: lists perform generally better in inserting, extracting and moving elements in any position within the container , The main drawback of lists compared to these other sequence containers is that they lack direct access to the elements by their position

16. stuct 和class中的指针需要指定成NULL

typedef struct Node
{
Node(int input):data(input),visit(0),lChild(NULL),rChild(NULL),parent(NULL){}
int data;
bool visit;
Node* lChild;
Node* rChild;
Node* parent;
};

17.If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a substring of T1. We can check this using a suffix tree.

 

18.string to int:

atoi(myString.c_str())

更方便的方式是使用stringstream

/* itoa example */
#include <stdio.h>
#include <stdlib.h>
// using stringstream constructors.
#include <iostream>
#include <sstream>
using namespace std;

int main () {

  int val;
  stringstream ss (stringstream::in | stringstream::out);

  ss << "120 42 377 6 5 2000";

  for (int n=0; n<6; n++)
  {
    ss >> val;
    cout << val*2 << endl;
  }

  return 0;
}19. static function: // static data members and functions belong to the class and
  // can be accessed without using an object of class X
  X::print_si();
  X::set_si(22);
  X::print_si();
A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared.
20.C++ constructors that have just one parameter automatically perform implicit type conversion.(It is also a implicit constructor if only one parameter doesn't have the default value)class Y {
  int a, b;
  char* name;
public:
  Y(int i) { };
  Y(const char* n, int j = 0) { };  //this is a implicit constructor too!
};You can add explicit to the constructor declaration to prevent implicit conversions. This forces the code to either use a parameter of the correct type, or cast the parameter to the correct type. That is, if the cast is not visibly expressed in code, an error will result.21.Typedef 用法总结>1:int *(*a[5])(int, char*);  定义一个数组,数组的成员是函数指针 >2:void (*b[10]) (void (*)()); 定义一个数组,数组成员是函数指针, 函数的参数是一个函数指针 >3. doube(*)() (*pa)[9]; 定义一个数组,数组成员是函数指针,函数的返回值是一个函数指针 1. typedef short SmallNumber;

2. typedef double* PDouble;

3. typedef string FiveStrings[5];// FiveString 代表一个大小为5的string数组

4. typedef double (*Addition)(double value1, double value2);  22. Private vs Protected:Protected members of a class A are not accessible outside of A's code, but is accessible from the code of any class derived from A(it will become B's protected or private member so it can be access by B's member function or friend).Private members of a class A are not accessible outside of A's code, or from the code of any class derived from A.So, in the end, choosing between protected or private is answering the following questions: How much trust are you willing to put into the programmer of the derived class?By default, assume the derived class is not to be trusted, and make your members private. If you have a very good reason to give free access of the mother class' internals to its derived classes, then you can make them protected.Sample code:class A {
public:
protected:
  int i;
};
class B : public A {
  friend void f(A*, B*);
  void g(A*);
};void f(A* pa, B* pb) {
//  pa->i = 1;
  pb->i = 2;//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}void B::g(A* pa) {
//  pa->i = 1;
  i = 2;//  int A::* point_i = &A::i;
  int A::* point_i2 = &B::i;
}void h(A* pa, B* pb) {
//  pa->i = 1;
//  pb->i = 2;
}int main() { }23. Linux System call:read:http://linux.die.net/man/2/readwrite:http://linux.die.net/man/2/writepipe, pipe2:http://linux.die.net/man/2/pipedup, dup2, dup3:http://linux.die.net/man/2/dupbind:http://linux.die.net/man/2/bindsocket:http://linux.die.net/man/2/socket
24. C++ Compilation Process: Preprocess -> Compile -> Assemble -> Link(More info, see link :http://faculty.cs.niu.edu/~mcmahon/CS241/Notes/compile.html)
25. Function overload: same name, different parameter(number/type). return type, function type doesn't matter.26.Binary Treesmedium complexity to implement (assuming you can't get them from a library)inserts are O(logN)lookups are O(logN)Linked lists (unsorted)low complexity to implementinserts are O(1)lookups are O(N)Hash tableshigh complexity to implementinserts are O(1) on averagelookups are O(1) on average27. Pointer VS ReferenceSummary from answers and links below:A pointer can be re-assigned any number of times while a reference can not be reassigned after initialization.A pointer can point to NULL while reference can never point to NULLYou can't take the address of a reference like you can with pointersThere's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).28. Map VS HashMap In c++They are implemented in very different ways.hash_map (unordered_map in TR1 and Boost; use those instead) use a hash table where the key is hashed to a slot in the table and the value is stored in a list tied to that key.map is implemented as a balanced binary search tree (usually a red/black tree).An unordered_map should give slightly better performance for accessing known elements of the collection, but a map will have additional useful characteristics (e.g. it is stored in sorted order, which allows traversal from start to finish). Unordered_map(O(1)) will be faster on insert and delete than a map(O(log n) ).
29. New Line:\n = CR (Carriage Return) // Used as a new line character in Unix
\r = LF (Line Feed) // Used as a new line character in Mac OS
\n\r = CR + LF // Used as a new line character in Windows
(char)13 = \n = CR // Same as \nEnvironment.NewLine = any of the above code based on the operating system 30. c++ priority queue:template <class T, class Container = vector<T>,
  class Compare = less<typename Container::value_type> > class priority_queue;TType of the elements.Aliased as member type priority_queue::value_type.ContainerType of the internal underlying container object where the elements are stored.Its value_type shall be T.Aliased as member type priority_queue::container_type.CompareA binary predicate that takes two elements (of type T) as arguments and returns a bool.The expression comp(a,b), where comp is an object of this type and a and b are elements in the container, shall return true if a is considered to go before b in the strict weak ordering the function defines.The priority_queue uses this function to maintain the elements sorted in a way that preserves heap properties (i.e., that the element popped is the last according to this strict weak ordering).This can be a function pointer or a function object, and defaults to less<T>, which returns the same as applying the less-than operator (a<b).

 

30. Copy constructors, assignment operators, and exception safe assignment


http://www.cplusplus.com/articles/y8hv0pDG/



strncmp VS string.compare()

strncmp:

Compares up to num characters of the C string str1 to those of the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ, until a terminating null-character is reached, or until num characters match in both strings, whichever happens first.

If argument n is specified , the first n characters in the array are used as the comparing string.
Otherwise , a null-terminated sequence is expected: the length of the sequence with the characters to use as comparing string is determined by the first occurrence of a null character.

 

31. Map VS Unordered Map

                     | map              | unordered_map
---------------------------------------------------------
element ordering       | strict weak      | n/a 
                       |                  |
common implementation  | balanced tree    | hash table
                       | or red-black tree|  
                       |                  |
search time            | log(n)           | O(1) if there are no hash collisions
                       |                  | Up to O(n) if there are hash collisions 
                       |                  | O(n) when hash is the same for any key
                       |                  |     
Insertion time         | log(n)+rebalance | Same as search
                       |                  | 
Deletion time          | log(n)+rebalance | Same as search
                       |                  | 
needs comparators      | only operator <  | only operator ==
                       |                  |
needs hash function    | no               | yes
                       |                  |
common use case        | when good hash is| In most other cases. 
                       | not possible or  | 
                       | too slow. Or when|
                       | order is required| 

32. Dynamic link lib vs Static link lib

Link editors are commonly known as linkers. The compiler automatically invokes the linker as the last step in compiling a program. The linker inserts code (or maps in shared libraries) to resolve program library references, and/or combines object modules into an executable image suitable for loading into memory. On Unix-like systems, the linker is typically invoked with the ld command.

Static linking is the result of the linker copying all library routines used in the program into the executable image. This may require more disk space and memory than dynamic linking, but is both faster and more portable, since it does not require the presence of the library on the system where it is run.

Dynamic linking is accomplished by placing the name of a sharable library in the executable image. Actual linking with the library routines does not occur until the image is run, when both the executable and the library are placed in memory. An advantage of dynamic linking is that multiple programs can share a single copy of the library.

  • Dynamic linking can reduce total resource consumption (if more than one process shares the same library (including the version in "the same", of course)). I believe this is the argument that drives it its presence in most environments. Here "resources" includes disk space, RAM, and cache space. Of course, if your dynamic linker is insufficiently flexible there is a risk of DLL hell.
  • Dynamic linking means that bug fixes and upgrades to libraries propagate to improve your product without requiring you to ship anything.
  • Plugins always call for dynamic linking.
  • Static linking, means that you can know the code will run in very limited environments (early in the boot process, or in rescue mode).
  • Static linking can make binaries easier to distribute to diverse user environments (at the cost of sending a large and more resource hungry program).
  • Static linking may allow slightly faster startup times, but this depends to some degree on both the size and complexity of your program and on the details of the OSs loading strategy.

33.

rvalue VS lvalue VS xvalue VS glvalue VS prvalue

An lvalue refers to an object that persists beyond a single expression. You can think of an lvalue as an object that has a name. All variables, including nonmodifiable (const) variables, are lvalues. An rvalue is a temporary value that does not persist beyond the expression that uses it. To better understand the difference between lvalues and rvalues, consider the following example:

  • An lvalue (so-called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue.]
  • An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references. [Example: The result of calling a function whose return type is an rvalue reference is an xvalue.]
  • glvalue (“generalized” lvalue) is an lvalue or an xvalue.
  • An rvalue (so-called, historically, because rvalues could appear on the right-hand side of an assignment expression) is an xvalue, a temporary object or subobject thereof, or a value that is not associated with an object.
  • prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [Example: The result of calling a function whose return type is not a reference is a prvalue]
34. Move constructor

http://en.cppreference.com/w/cpp/language/move_constructor




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值