简体   繁体   中英

std::transform behaviour along with back_inserter not understanding

I have a trouble in understanding the behaviour of transform function if used with back_inserter.

#include <algorithm> 
using namespace std;

int main()
{
    vector<int> a{1,2,4};
    transform(begin(a), end(a), back_inserter(a), [](auto e){ cout << e << "-" ;
                                                             return e;});
    return 0;
}

In the above program, I get the output as 1-0-4. I am not able to understand how this 0 is coming? Please see live example cpp.sh/6vpzk

This code does vector::push_back while iterating over it using its iterators. vector::push_back invalidates all existing iterators causing undefined behaviour, and that is where that 0 comes from (it can be any other number, since the behaviour is undefined).

You should probably use for_each or range for loop.

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