您的位置:首页 > 编程语言

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

2013-10-15 22:11 351 查看
转自: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++中数组下标也可为负值,这也会导致出错。

#include<fstream>
#include<iostream>
#include<string>
using namespace std;
#define N 100
int data
;
unsigned int from
;
unsigned int to
;

int main(void)
{
unsigned int top=0;
unsigned int a;
string file,ofile;
cin>>file>>ofile;
ifstream infile;
ofstream outstream;
infile.open(file.c_str());
outstream.open(ofile.c_str());
while(infile>>a)
{
/* test signed []
unsigned int *p=&from[1];
from[0]=1;
cout<<p[a]<<endl;
*/
//cout<<to[from[a]]<<endl;
if(from[a]<top&&to[from[a]]==a)
{
cout<<a<<"has been used!"<<endl;
}
else{
data[a]=1;
from[a]=top;
to[top]=a;
top++;
}
}
for(int i=0;i<N;i++)
{
outstream<<data[i]<<"  ";
}
outstream<<endl;
outstream.seekp(0,ios::cur);
for(i=0;i<N;i++)
{
outstream<<from[i]<<"  ";

}
outstream<<endl;
for(i=0;i<top;i++)
{
outstream<<to[i]<<"  ";
}
outstream<<endl;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: