c++ - std::transform producing strange output -


Today I was playing with some standard library functions .. And this strange output std :: transform () and std: : Back_inserter When using container (vector in this case) there are more than 2 elements. I do not understand this kind of behavior, anyone can help me ...

  Include # lt; Iostream & gt; # Include & lt; Algorithm & gt; #to & lt include, vector & gt; using namespace std; / * This version of the change works fine for me when I change the variable value to the variable variable ant (int n) {static int m = n; Return M * M; } * / Int change (int n) {return n * n; } Int main () {Vector & lt; Int & gt; V2 (3,3), v1; Transform (v2.begin (), v2.end (), back_inserter (v2), change); (Auto v: v2) {cout & lt; & Lt; V  

Most likely is that vector Loading when you specify it in the push_back elements (which in the back_insert_iterator results). This start and finished iterators have been passed to changes , and the subsequent assignment result is invalid in undefined behavior.

Your problem change

  vector & lt; Before calling,  reserve ()  adequate code  integer & gt; V2 (3,3); V2.reserve (v2.size () * 2); Transform (v2.begin (), v2.end (), back_inserter (v2), change); 

div>

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -