使用来自其他 class 的向量作为反向迭代器

Using vector from other class as reverse iterator

抱歉,我如履薄冰。我以前没有使用过反向迭代器,就像你在我的代码中看到的那样,我还想使用来自另一个 class 的向量作为迭代器对象:

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;
}

但是当我编译这段代码时,我得到了几个这样的错误: 错误:“operator[]”不匹配(操作数类型为“std::vector”和“std::vector::reverse_iterator {aka std::reverse_iterator<__gnu_cxx::__normal_iterator > >}'), 指向我的矢量索引??

if (Close1->Close[i] < Close1->Close[(i + 1)]){

就像我说的,这对我来说是新领域,我想错误在于迭代器的声明? 当我在其他代码中遍历相同的向量(从前到后)时,没有问题。 非常感谢帮助!

std::vector 的方括号运算符接受索引,而不是迭代器。

这里您尝试使用迭代器作为索引:

if (Close1->Close[i] < Close1->Close[(i + 1)]) {

与其将迭代器传递给运算符 [],不如使用星号取消引用它们,以便获得它们指向的向量元素:

if (*i < *(i + 1)) {

此外,取消引用 i + 1 时要小心:在循环的最后一次迭代中,i + 1 将等于 rend()(反向过去的最后一个元素迭代器)。尝试通过此类迭代器访问任何内容将导致未定义的行为。

要看看你做错了什么,请注意这两个是等价的

int main(){
    vector<int> myVec {{1,2,3,4}};
    //read then print each value in vector
    for(vector<int>::iterator i=myVec.begin();i!=myVec.end(); ++i){
    //here i is an iterator not an index
         int val = *i; //get value in current position within vector
         cout<<val<<endl;
    }

    for(int i=0; i!=myVec.size(); ++i){
    // here i is an index
         int val = myVec[i];//get value in current position within vector
         cout<<val<<endl;
    }

 }

在你的例子中使用“*i”而不是"Close1->Close[i]"来读取值