简体   繁体   中英

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/.

To do this, I firstly copy the vector vec and then iterate in this way:

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. 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.

PS From the main I am passing an initialized vector with double values.

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. It is possible for different functions, like std::prev or the dereference operator, to handle this differently. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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