使用STL中的array模板类

需求是输入四个季节的支出并显示支出,所有的数据都用 array 模板类对象来存储

代码如下:

//array.cpp --  functions with array objects

#include <iostream>
#include <array>
#include <string>

//constant data 
const int Seasons = 4;
const std::array<std::string, Seasons> Snames = 
{"Spring", "Summer", "Fall", "Winter"};

void fill ( std::array<double, Seasons> * pa);
void show ( std::array<double, Seasons> da );

int main()
{
 std::array< double, Seasons> obj;
 fill( &obj );
 show( obj );
 std::cin.get();
 std::cin.get();
 return 0;

}
void fill ( std::array<double, Seasons> * pa)
{
	using namespace std;
	for (int i = 0; i < Seasons; i++)
	{
		cout << "Enter " << Snames[i] << " expenses: ";
		cin >> (*pa)[i]; // 这个写法有点不理解,不能写成 cin >> pa[i] 或者 cin >> *(pa + i)吗?
		//cin >> *( pa + i); 错误,为什么错?
	}

}
void show ( std::array<double, Seasons> da )
{
	using namespace std;
	double total = 0.0;
	cout << "\nEXPENSES\n";
	for (int i = 0; i < Seasons; i++)
	{
		cout << Snames[i] << " expenses is: " << da[i] << endl;
		total += da[i];
	}
	cout << "Total expenses is: " << total << endl;

}

运行效果如图:

使用STL中的array模板类_第1张图片


你可能感兴趣的:(C++,array,STL)