您的位置:首页 > 其它

Cranking The Coding Interview: 12

2017-03-04 10:05 232 查看
12-1
题目

题目解答

12-9
smart 指针

代码实现

12-1

题目

读取一个文件的最后k行。

题目解答

#include <iostream>
#include <fstream>
using namespace std;

void printLastKLines(ifstream &fin, int k){
string line[k];
int lines = 0;
string tmp;
while(getline(fin, tmp)){
line[lines%k] = tmp;
++lines;
}
int start, cnt;
if(lines < k){
start = 0;
cnt = lines;
}
else{
start = lines%k;
cnt = k;
}
for(int i=0; i<cnt; ++i)
cout<<line[(start+i)%k]<<endl;
}
int main(){
ifstream fin("13.1.in");
int k = 4;
printLastKLines(fin, k);
fin.close();
return 0;
}


这里没有使用eof来判断文件的结束,因为eof()函数是在fin中已经没有内容可输入时,才被置为true。 如果使用上面的循环,getline在读入最后一行后,由于这一行仍然是有内容的, 所以eof()返回的仍然为false,表示还没到文件结尾。然后会再进入循环一次, 这时getline读入一个空串,已经没有内容可输入,eof()返回true而退出循环。 结果就是因为多读入一个空串,line数组中保存的是最后k-1行再加一个空串, 两个字:错误。如果我们将循环改成printLastKLines中的样子,那就没问题了。

12-9

smart 指针

写一个智能指针类(smart_ptr)。

代码实现

#include <iostream>
#include <cstdlib>
using namespace std;

template <typename T>
class SmartPointer{
public:
SmartPointer(T* ptr){
ref = ptr;
ref_count = (unsigned*)malloc(sizeof(unsigned));
*ref_count = 1;
}

SmartPointer(SmartPointer<T> &sptr){
ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}

SmartPointer<T>& operator=(SmartPointer<T> &sptr){
if (this != &sptr) {
if (--*ref_count == 0){
clear();
cout<<"operator= clear"<<endl;
}

ref = sptr.ref;
ref_count = sptr.ref_count;
++*ref_count;
}
return *this;
}

~SmartPointer(){
if (--*ref_count == 0){
clear();
cout<<"destructor clear"<<endl;
}
}

T getValue() { return *ref; }

private:
void clear(){
delete ref;
free(ref_count);
ref = NULL; // 避免它成为迷途指针
ref_count = NULL;
}

protected:
T *ref;
unsigned *ref_count;
};

int main(){
int *ip1 = new int();
*ip1 = 11111;
int *ip2 = new int();
*ip2 = 22222;
SmartPointer<int> sp1(ip1), sp2(ip2);
SmartPointer<int> spa = sp1;
sp2 = spa; // 注释掉它将得到不同输出
return 0;
}


参考链接:

【1】12.1 : http://www.hawstein.com/posts/13.1.html

【2】12.9 : http://www.hawstein.com/posts/13.9.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cc 12