简体   繁体   English

在C ++中迭代向量并动态更改值

[英]Iterating over a vector in C++ and changing the values dynamically

I am writing a c++ method that takes a vector vec of type T and returns a "delta" vector, ie vector with element vec(i)-vec(i-1) at position i, i>0 /I set the element at 0 to be the same as the one at 1/. 我正在编写一个c ++方法,该方法采用类型T的向量vec并返回“增量”向量,即在位置i,i> 0处具有元素vec(i)-vec(i-1)的向量,将元素设置为0与1 /相同。

To do this, I firstly copy the vector vec and then iterate in this way: 为此,我首先复制向量vec,然后以这种方式进行迭代:

template<class T>
vector<T> delta(vector<T> vec){
    vector<T> result(vec);
    for (typename vector<T>::iterator i = result.end(); i >= result.begin()+1; i--)
        {
            *i = *i - *(std::prev(i));
        }

    result.at(0) = result.at(1);
    return (result);
}

There seems to be some problem with the line 这条线似乎有问题

*i = *i - *(std::prev(i));

which I don't understand. 我不明白。 If I change it to *i = *i - 1 it works fine. 如果我将其更改为* i = * i-1,则效果很好。 The other problem is that the program just fails without showing me errors (it pops a window with "main.exe has stopped working". I am using CLion IDE. 另一个问题是该程序只是失败而没有显示我错误(它弹出一个带有“ main.exe已停止工作”的窗口。)我正在使用CLion IDE。

PS From the main I am passing an initialized vector with double values. PS从主要方面,我正在传递带有双精度值的初始化向量。

This is undefined behavior. 这是未定义的行为。 When you set your iterator to result.end(), you are dereferencing an end iterator to your vector, which is essentially the area in memory directly after your vector. 当将迭代器设置为result.end()时,您是在将终止迭代器解引用到向量,该向量本质上是向量之后紧随其后的内存区域。 It is possible for different functions, like std::prev or the dereference operator, to handle this differently. 诸如std :: prev或解引用运算符之类的不同函数可能会对此进行不同的处理。 To eliminate this behavior, try this loop: 要消除这种现象,请尝试以下循环:

for (typename std::vector<T>::iterator i = result.end()-1; i >= result.begin()+1; i--) {
         *i = *i - *(i-1);
}

This loop simply starts at the last valid position in the vector (the end iterator -1). 该循环仅从向量中的最后一个有效位置开始(结束迭代器-1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM