I'm on thin ice here, Sorry. I have not used reverse iterators before, and like you can see in my code is that I also want to use a vector from another class as THE iterator object:
double indicators::sRSItemp(input* Close1, int StartDay) {
int n = 14;
double rs;
double rsi;
double tmpavl;
double tmpavg;
if (!RSI.empty()) {
for ( vector<double>::reverse_iterator i = Close1->Close.rbegin(); i != Close1->Close.rend(); ++i ) {
if (Close1->Close[i] < Close1->Close[(i + 1)]){
tmpavl = ((AVL[0] * 13 ) + (Close1->Close[(i +1)] - Close1->Close[i] ) / n);
cout << "AVLtmp " << AVL[0] << endl;
cout << "tmpavl " << tmpavl << endl;
AVL.insert(AVL.begin(), tmpavl);
cout << "AVL is " << AVL[0] << endl;
tmpavg = ((AVG[0] * 13 ) / n );
AVG.insert(AVG.begin(), tmpavg);
// cout << "AVG is " << AVG[i] << endl;
}
else if (Close1->Close[i] > Close1->Close[(i + 1)]) {
tmpavg = ((AVG[0] * 13 ) + (Close1->Close[i] - Close1->Close[(i +1)]) / n );
AVG.insert(AVG.begin(), tmpavg);
// cout << "AVG is " << AVG[i] << endl;
tmpavl = ((AVL[0] * 13 ) / n );
AVL.insert(AVL.begin(), tmpavl);
// cout << "AVL is " << AVL[i] << endl;
}
rs = AVG[0] / AVL[0];
rsi = (100.0 - (100.0 / (1.0 + rs)));
RSI.insert(RSI.begin(), rsi);
}
}
return 0;
}
But when I compile this code I get several errors like this : error: no match for ‘operator[]’ (operand types are ‘std::vector’ and ‘std::vector::reverse_iterator {aka std::reverse_iterator<__gnu_cxx::__normal_iterator > >}’), pointing to my vector indexing ??
if (Close1->Close[i] < Close1->Close[(i + 1)]){
Like I said this is new territory for me, and the fault I guess lies with the declaration of the iterator ? When I iterate through the same vector (front-to-back) in other code there are no problems. Help much appreciated!
The square brackets operator of std::vector
accepts indexes, not iterators.
Here you're trying to use iterators as indexes:
if (Close1->Close[i] < Close1->Close[(i + 1)]) {
Instead of passing iterators to operator [], you should just use asterisks to dereference them, in order to get to vector elements they are pointing to:
if (*i < *(i + 1)) {
Also, be careful with dereferencing i + 1
: on the last iteration of your loop i + 1
will be equal to rend()
(the reverse past-the-last element iterator). Attempting to access anything via such an iterator will result in undefined behavior.