转-编程珠玑第一章习题9

转自:http://m.blog.csdn.net/blog/dawn_cx/8943273

对于十分稀疏的数组,按照数组下标值存入和读取数组元素。当读取数组元素时,如何不需要初始化就能判断该值是存入的还是脏数据,就需要用到下面的方法,用空间换时间。

如果不用这个方法,必须对数组初始化,然后判断读取的值跟初始化值的区别,来确定该值是否是存入值。但当数据十分稀疏时,初始化过程会浪费大量的时间。

一个自然的想法就是能不能用一个数组记录下已经初始化的位置,这就是to【N】数组的作用。按照初始化顺序,保存初始化的位置,用top指针来标记有效数据。但仅有to数组还不能达到读取时的随机性,如果没有from数组,只能顺序遍历to数组,来判断是否初始化。

利用from数组,将to数组与data数组联系起来,例如要取data【3】,to里面如果存着3这个值,表明已经初始化过,但如何快速的找到to里面的3。只要看from【3】中存储的值,该值就是to中存3的位置。

另外,from和to由于都是存储位置下标,因此为unsigned int。

C++中,unsigned int是可以被int类型赋值的,赋值结果是int型(mode 32)后的值,这样就可能导致出错,所以输入和top元素也都设置为unsigned int。

C++中数组下标也可为负值,这也会导致出错。

 1 #include<fstream>
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 #define N 100
 6 int data[N];
 7 unsigned int from[N];
 8 unsigned int to[N];
 9 
10 int main(void)
11 {
12     unsigned int top=0;
13     unsigned int a;
14     string file,ofile;
15     cin>>file>>ofile;
16     ifstream infile;
17     ofstream outstream;
18     infile.open(file.c_str());
19     outstream.open(ofile.c_str());
20     while(infile>>a)
21     {
22         /* test signed []
23         unsigned int *p=&from[1];
24         from[0]=1;
25         cout<<p[a]<<endl;
26         */
27         //cout<<to[from[a]]<<endl;
28         if(from[a]<top&&to[from[a]]==a)
29         {
30             cout<<a<<"has been used!"<<endl;
31         }
32         else{
33         data[a]=1;
34         from[a]=top;
35         to[top]=a;
36         top++;
37         }
38     }
39     for(int i=0;i<N;i++)
40     {
41         outstream<<data[i]<<"  ";
42     }
43     outstream<<endl;
44     outstream.seekp(0,ios::cur);
45     for(i=0;i<N;i++)
46     {
47         outstream<<from[i]<<"  ";
48 
49     }
50     outstream<<endl;
51     for(i=0;i<top;i++)
52     {
53         outstream<<to[i]<<"  ";
54     }
55     outstream<<endl;
56 }

 

原文地址:https://www.cnblogs.com/cavehubiao/p/3371140.html