马上就要毕业了,找工作的压力随之而来,这段时间决定好好准备一下,记一下学习笔记,开始吧。
一、operator = 函数
直接上代码:
CMyString& CMyString::operator=(const CMyString &str)
{
if (this != &str)
{
CMyString strTemp(str);
char* pTemp = strTemp.m_pData;
strTemp.m_pData = m_pData;
m_pData = pTemp;
}
return *this;
}
要点:
1、返回值应该声明为该类型的引用,并返回*this,这样才可以连续赋值。
2、参数为const引用
3、先判断是否为本身赋值
4、建立临时变量先把str给临时变量(通过copy constructor)然后交换指针指向,这样做的好处是可以保证“异常安全”,if结束strTemp被析构,释放原先m_pData的内容
二、Singleton模式
代码如下:
class Singleton
{
public:
~Singleton(){}
static Singleton* Instance()
{
if (_instance == NULL)
{
_instance = new Singleton();
}
return _instance;
}
protected:
Singleton(){}
static Singleton* _instance;
};
Singleton* Singleton::_instance = NULL;
要点:
1、constructor函数设置为protected,至于为何不是private,是因为这样可以作为基类被继承,详见《more effective c++》
2、不要忘记静态成员变量的初始化。
三、关于数组
int GetSize(int data[])
{
return sizeof(data);
}
int data1[] = {1,2,3,4,5};
int *data2 = data1;
print
sizeof(data1);
sizeof(data2);
GetSize(data1);
输出20,4,4 最后一个是4,因为数组作为参数传递时退化为指针,C/C++没有记录数组大小,用指针访问时,程序员要确保没有越界访问。
四、关于字符串
char str1[] = "hello world";
char str2[] = "hello world";
char *str3 = "hello world";
char *str4 = "hello world";
str!=str2
str3 == str4
不难理解,str1和str2地址不同,分配有个自己的空间,str3和str4指向的是字符串常量,内存中地址相同。
五、替换字符串中的空格
We are happy输出We%20are%20happy
时间复杂度为O(n)的算法是,先计算出替换后的总长,然后从后往前复制,遇到空格就加入%20。
给人的第一印象就是从前往后找,遇到空格就替换,这样时间复杂度为O(n2),有时候思维应该灵活一点。
六、由二叉树的前序和中序遍历结果重建二叉树
以前在九度OJ的AC代码(递归实现):
#include <stdio.h>
#include <iostream>
#include <string>
#include <list>
#include <vector>
using namespace std;
typedef struct Node
{
int num;
struct Node* left;
struct Node* right;
}Node;
typedef vector<int> VI;
VI F;
VI M;
static int index = 0;
bool isBiTree;
Node* CreateBiTree( VI M)
{
if (M.size() == 0)
return NULL;
int num = F[index];
index++;
VI l;
VI r;
VI::iterator iter;
iter=M.begin();
while( iter != M.end() && (*iter) != num)
{
l.push_back(*iter);
++iter;
}
if (iter == M.end())
{
isBiTree = false;
return NULL;
}
++iter;
while (iter != M.end())
{
r.push_back(*iter);
++iter;
}
Node *node = new Node;
node->num = num;
if (l.size() == 0)
node->left = NULL;
else
node->left = CreateBiTree(l);
if (r.size() == 0)
node->right = NULL;
else
node->right = CreateBiTree(r);
return node;
}
void LastPrint(Node* node)
{
if (node==NULL)
return;
LastPrint(node->left);
LastPrint(node->right);
printf("%d ",node->num);
}
int main(int argc, char* argv[])
{
int n,num,i;
while( scanf("%d", &n) != EOF )
{
F.clear();
M.clear();
index = 0;
isBiTree = true;
for (i=0; i<n; ++i)
{
scanf("%d", &num);
F.push_back(num);
}
for (i=0; i<n; ++i)
{
scanf("%d", &num);
M.push_back(num);
}
Node* node = CreateBiTree(M);
if (isBiTree == false)
{
printf("No\n");
}
else
{
LastPrint(node);
printf("\n");
}
}
}