编程珠玑第二章A题

二分法,按位二分,时间复杂度o(N),空间复杂度临时变量。

文件流,以输出流形式打开文件时,源文件内容会被清空;输入输出流形式,源文件内容只是覆盖。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int get_lost(string file1,string file2,string file3,int length,int bit)
{
	int lost=0;
	int f2_count,f3_count;
	int a;
	ifstream f1(file1.c_str());
	if(!f1)
	{
		cerr<<"can not open file: "<<file1<<endl;
		return -1;
	}
	ofstream f2(file2.c_str());
	if(!f2)
	{
		std::cerr<<"can not open file: "<<file2<<endl;
		return -1;
	}
	ofstream f3(file3.c_str());
	if(!f3)
	{
		std::cerr<<"can not open file: "<<file3<<endl;
		return -1;
	}
	if(length==(unsigned long)(1<<bit))
		return -1;
	while(bit--){
		f2_count=0,f3_count=0;
		//cout<<"round  "<<bit<<endl;
	for(int i=0;i<length;i++)
	{
        f1>>a;
	//	cout<<a<<endl;
		if(a&(1<<bit))
		{
			
			f2<<a<<endl;
            f2_count++;
			
		}
		else{
			f3<<a<<endl;
		    f3_count++;
		}
	}
//	int tmp;
//	cout<<"f2_count"<<f2_count<<endl;
	/*f2.seekg(0,ios::beg);
	while(f2>>tmp)
	{
		
		cout<<tmp<<endl;
		cout<<"-------------------------------"<<endl;
	}
	f3.seekg(0,ios::beg);
	cout<<"f3_count"<<f3_count<<endl;
	while(f3>>tmp)
	{
		
		cout<<tmp<<endl;
		cout<<"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;
	}*/
	f1.close();
	f2.close();
	f3.close();
	f1.clear();
	f2.clear();
	f3.clear();
	if(f2_count<=f3_count)
	{
		length=f2_count;
		f1.open(file2.c_str());
		f2.open(file1.c_str());
		f3.open(file3.c_str());
		lost+=(1<<bit);
		//cout<<"lost  "<<lost;
	}
	else{
		length=f3_count;
		f1.open(file3.c_str());
		f2.open(file2.c_str());
		f3.open(file1.c_str());
		lost+=(0<<bit);
	//	cout<<"lost  "<<lost;
	}
	}
	return lost;
}
int main(void)
{
	string ifile;
	string tmp="tmp.txt",tmp2="tmp2.txt";
    cin>>ifile;
	cout<<get_lost(ifile,tmp,tmp2,14,4)<<endl;
	//一下内容测试文件流,何时覆盖、何时清空文件
	fstream test("tmp3.txt");
	for(int i=0;i<10;i++)
	{
		test<<i<<endl;
	}
    test.close();
	test.clear();
	test.open("tmp3.txt");
	test<<"1"<<endl;//不清空
    ofstream test2("tmp3.txt");
	test2<<"2"<<endl;//清空


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值