Shifting Elements in Array that Keeps History;

Say I have a history array of 10 indexes; when I fill the array with values up to the last index {0,1,2,3,4,5,6,7,8,9} and I "keep" updating the array for the last index {9} and replace it with a new value {10} while shifting the whole array into the same named array; but with the new value in the last index {1,2,3,4,5,6,7,8,9,10}.

I'm able to capture my operations history; but I'm unable to think of a way to keep updating the array whenever I exceed it's history length to keep only the last 10 operations. I understand how to assign the value to the last index; but I'm unable to create an operation to shift the initial indexes.
Any tips?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double Account::operator+=(double value){
//overload +=
	if ((value < 0) && abs(value)>balance){
	throw balance;
	}
	balance = balance + value;
	
	history[index] = balance;
	index++ ;
	
	//(index==10){
	//	index = 0;
	//	}
	
	return balance;
	
	
	}  


This is part of the way there; but this overwrites from the first index, and doesn't shift the other indexies.
use standard algorithm std::rotate:
http://en.cppreference.com/w/cpp/algorithm/rotate
For example shifting history to the left and overwriting last entry:
1
2
std::rotate(history, history + 1, history + 10);
history[9] = balance;
1
2
3
4
5
std::queue<double> foo;

foo.push(42);
if( foo.size() > 10 )
   foo.pop();


A queue may be implemented with a circular array, and two index. When pushing you increase the `back' index, when popping you increase the `front' index
(increase in a circular way K = (K+1) % n;)


> but I'm unable to create an operation to shift the initial indexes.
you may be shifting as erasing the first element.
v[K] = v[K+1] // K=0..n-2
Last edited on
Maybe you should have history be a queue instead. Then you'll just pop the first element whenever the size exceeds 10.

Otherwise, I guess you'll need a loop in your function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double Account::operator+=(double value){
	//overload +=
	if ((value < 0) && abs(value)>balance){
		throw balance;
	}
	balance = balance + value;

	for (int index = 0; index < 9; ++index){
		history[index] = history[index + 1];
	}
	history[9] = balance;

	return balance;
}


For it to work properly, you would need to initialize the history array to all zeroes in your constructor.
Resolved; thank you for the hasty response. So the idea is to fill the array backwards while assigning the value to the last element in the array, then the loop will shift the indexes when it will be assigned an new balance. Thank you for the big help.
Last edited on
Topic archived. No new replies allowed.