天天看點

用時間空間複雜度為1的算法讓順序表逆置

今天看到一到有意思的題

用時間空間複雜度為1的算法讓順序表逆置

雖然和題意不大對(因為要位置變換,我這種想法不算真正的位置變換)但是感覺很有意思。

其實就是重載運算符

#pragma once
#define MAXSIZE 50

#include<string.h>
template <typename ElemType>
struct Sequence
{
public:
	ElemType data[MAXSIZE];
	int length;
	ElemType& (Sequence::*Index)(int)= &Sequence::IndexR1;

	Sequence(ElemType *A,int size)
	{
		memcpy(data, A,  size * sizeof ElemType);
		length = size;
	}
	bool ReverseIndex(bool t)
	{
		if (t == true)
		{
			Index = &Sequence::IndexR2;
		}
		else
		{
			Index = &Sequence::IndexR1;
		}
		return t;
	}
	ElemType& operator[](int i)
	{
		return (this->*Index)(i);
	}
private:

	ElemType& IndexR1(int i)
	{
		return data[i];
	}

	ElemType& IndexR2(int i)
	{
		return data[length - i - 1];
	}
	/*記:讀取成員函數指針需要使用  &Sequence::
		定義函數指針記得給函數名和*加括号
		定義成員函數指針需要在名字的括号裡面有 Sequence::
		使用類成員函數指針需要 (this->*Index) 一定要有括号否則優先與右邊的括号結合報錯,this可以替換成執行個體裡的虛函數等。


	*/
};
	
int main()
{
	int B[] = { 1,2,3,4,5,6,7,8,9,10 };
	Sequence<int> A(B,10);
	cout << A[3];
	A.ReverseIndex(true);
	cout << A[3];
	A.ReverseIndex(false);
	cout << A[3];

}
           

繼續閱讀