算法和数据结构项目练习3-数组虚拟初始化

Array Virtual Initialization

项目介绍

  1. 这个项目将实现一个虚拟初始化数组并测试它的正确性。

  2. 使用三个整数数组:data[]、forward[]和backward[],每个数组包含100个元素。

  3. txt文件包含一组成对的:where ,what。使用虚拟初始化将值what存储在数据数组的位置中。例如data[where] = what。

  4. 这个序列被一对-1 -1终止。

  5. 后面跟着一个单整数值序列probe。对于每个这样的值,您需要测试data[probe]是否已经初始化,并打印以下两条消息之一:

    1. 位置probe未初始化。
    2. 位置探probe已初始化为数值data[probe]
  6. 该序列以值-1结束。

举个例子:

读取一个txt文件,右侧的一列为data[x]数组中x的位置,左侧的一列为数组的值。
数组的读取到-1,-1终止。

probe为:
5,17, 24,42,99
序列以值-1结束。

读取的txt部分如下:
在这里插入图片描述
经过程序输出的格式应为:
Position 5 has not been initialized.

Position 17 has …

Position 24 has …

Position 42 has …

Position 99 has …

代码实现

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//use three integer arrays, data[], forward[] and backward[] each containing 100 elements
const int MAXWORDS = 100;//max words in array
int Array_data[MAXWORDS];
int Array_forward[MAXWORDS];
int Array_backward[MAXWORDS];


int main()
{

	string a;
	cout << "Please enter the filename: " << endl;
	cin >> a;

	ifstream read;
	read.open(a.c_str());
	if (!read)
	{
		cout << "Can't open file" << endl;
		exit(1);
	}

	int index = 1;
	int vcn = 0;//valid count number
	int x = 0, y = 0;
	while (!read.eof())
	{
		while (index < 100)
		{
			if (read.fail())break;
			read >> y;
			read >> x;
			if (x == -1 && y == -1)// terminated by the value -1
				break;

			vcn++;
			Array_data[x] = y;//where  what
			Array_forward[vcn] = x;
			Array_backward[x] = vcn;
			index++;
		}


		int i = 0;
		while (i < 100) {
			read >> x;
			
			if (x == -1)// terminated by the value -1
				break;
			i++;
			if (Array_backward[x] > 0 && Array_backward[x] <= vcn && Array_forward[Array_backward[x]] == x)
			{
			cout << "Position " << x << " has been initialized to value " << Array_data[x] << "." << endl;
			}
			else
			{
			cout << "Position " << x << " has not been initialized." << endl;
			}

		}
		
	}
	read.close();



	return 0;
}








程序输出如下:
在这里插入图片描述)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值