static和引用&,指针*应用实例:输出数列的项

函数pentegonal=n(3n-1)/2. 以局部静态(local static)的vector存储pentegonal的元素。写一个函数,返回一个const指针,指向改vector。如果该vector的元素个数小于指定的元素个数,则扩充vector的个数。另写一个函数,接收一个位置值,返回改位置上的元素。最后,写一个main函数,测试这些函数。

#include<iostream>
#include<vector>
using namespace std;

bool check_validity(int pos)
{
	return ((pos <= 0 || pos > 64) ? false : true);
}
const vector<int>*pentagonal_series(int pos)
{
	static vector<int> _elems;
	if (check_validity(pos) || _elems.size() < pos)
		for (int ix = _elems.size() + 1; ix <= pos; ix++)
		{
			_elems.push_back((ix*(3 * ix - 1)) / 2);
		}
	return &_elems;
}
int pentagonal_elem(int pos, int &elem)//按题目要求确定参数和返回值,功能
{
	if (!check_validity(pos))
	{
		cerr << "sorry!invalidity postion " << pos << endl;
		elem = 0;
		return false;
	}
	const vector<int>* pent = pentagonal_series(pos);//又定义了一个vector;
	elem = (*pent)[pos - 1];
	return true;
}
int main()
{
	int elem;
	if (pentagonal_elem(8, elem))
		cout << "the elem in position 8 :" << elem << endl;
	if (pentagonal_elem(66, elem))
		cout << "the elem in position 66 :" << elem << endl;
	getchar();

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值