文件中有一组整数,要求排序后输出到另一个文件中(从大到小)

本文介绍了一个具体的案例,展示了如何通过C++实现文件的读写操作,并运用冒泡排序算法对读取的数据进行排序,最后将排序结果保存到新文件中。文中详细解释了排序算法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目考查对文件的操作和对排序算法的使用

排序前文件的整数:15 23 16 7 8 11 2 4 97 10 21 13 25 70 15 1

1.冒泡排序:

//冒泡排序 从大到小
void BubbleSort(vector<int>&data)
{
	int length = data.size();
	for (int i = 0; i < length-1; i++)
	{
		for (int j = 0; j < length-1-i; j++)
		{
			if (data[j] < data[j + 1])
			{
				int temp = data[j];
				data[j] = data[j + 1];
				data[j + 1] = temp;
			}
		}
	}
}

2.打开文件并将数据放到vector中

vector<int> data;
	ifstream m_in("E:/vccode/numdata.txt");

	if (!m_in)//未读取到文件
	{
		cout << "could not open file" << endl;
		system("pause");
		exit(1);
	}

	int temp;
	while (!m_in.eof())
	{
		m_in >> temp;
		data.push_back(temp);
	}
	m_in.close();

3.调用排序算法

//利用算法sort排序
	//sort(data.begin(), data.end(),greater<int>());
	
	//利用冒泡
	BubbleSort(data);

4.将排序后的结果存储到新的文件中

ofstream m_out("E:/vccode/resultnumdata.txt");//输出到指定文件
	if (!m_out)
	{
		cout << "could not save file" << endl;
		system("pause");
		exit(1);
	}
	//输出排序后的结果
	for (int i = 0; i < data.size(); i++)
	{
		m_out << data[i] << " ";
	}
	m_out.close();

排序后新文件的整数:97 70 25 23 21 16 15 15 13 11 10 8 7 4 2 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值