File tree Expand file tree Collapse file tree 4 files changed +103
-0
lines changed Expand file tree Collapse file tree 4 files changed +103
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < fstream>
3
+ using namespace std ;
4
+
5
+ void printLastKLines (ifstream &fin, int k){
6
+ string line[k];
7
+ int lines = 0 ;
8
+ string tmp;
9
+ while (getline (fin, tmp) && !fin.eof ()){
10
+ line[lines%k] = tmp;
11
+ ++lines;
12
+ }
13
+ int start, cnt;
14
+ if (lines < k){
15
+ start = 0 ;
16
+ cnt = lines;
17
+ }
18
+ else {
19
+ start = lines%k;
20
+ cnt = k;
21
+ }
22
+ for (int i=0 ; i<cnt; ++i)
23
+ cout<<line[(start+i)%k]<<endl;
24
+ }
25
+ int main (){
26
+ ifstream fin (" 13.1.in" );
27
+ int k = 4 ;
28
+ printLastKLines (fin, k);
29
+ fin.close ();
30
+ return 0 ;
31
+ }
Original file line number Diff line number Diff line change
1
+ one
2
+ two
3
+ three 3
4
+ last 4 lines:begin
5
+ the second line
6
+ continue
7
+ end
Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < cstdlib>
3
+ using namespace std ;
4
+
5
+ template <typename T>
6
+ class SmartPointer {
7
+ public:
8
+ SmartPointer (T* ptr){
9
+ ref = ptr;
10
+ ref_count = (unsigned *)malloc (sizeof (unsigned ));
11
+ *ref_count = 1 ;
12
+ }
13
+
14
+ SmartPointer (SmartPointer<T> &sptr){
15
+ ref = sptr.ref ;
16
+ ref_count = sptr.ref_count ;
17
+ ++*ref_count;
18
+ }
19
+
20
+ SmartPointer<T>& operator =(SmartPointer<T> &sptr){
21
+ if (this != &sptr) {
22
+ if (--*ref_count == 0 ){
23
+ clear ();
24
+ cout<<" operator= clear" <<endl;
25
+ }
26
+
27
+ ref = sptr.ref ;
28
+ ref_count = sptr.ref_count ;
29
+ ++*ref_count;
30
+ }
31
+ return *this ;
32
+ }
33
+
34
+ ~SmartPointer (){
35
+ if (--*ref_count == 0 ){
36
+ clear ();
37
+ cout<<" destructor clear" <<endl;
38
+ }
39
+ }
40
+
41
+ T getValue () { return *ref; }
42
+
43
+ private:
44
+ void clear (){
45
+ delete ref;
46
+ free (ref_count);
47
+ ref = NULL ; // 避免它成为迷途指针
48
+ ref_count = NULL ;
49
+ }
50
+
51
+ protected:
52
+ T *ref;
53
+ unsigned *ref_count;
54
+ };
55
+
56
+ int main (){
57
+ int *ip1 = new int ();
58
+ *ip1 = 11111 ;
59
+ int *ip2 = new int ();
60
+ *ip2 = 22222 ;
61
+ SmartPointer<int > sp1 (ip1), sp2 (ip2);
62
+ SmartPointer<int > spa = sp1;
63
+ sp2 = spa;
64
+ return 0 ;
65
+ }
You can’t perform that action at this time.
0 commit comments