c++ - How to have valid .begin() and .end() without .resize() for std::vector? -


Do I want to use a function function for my vector and still want to use an iterator without resizing Am I blaming my previous values?

Is it possible or is I missing a point in STL design?

  #include & lt; Vector & gt; # Include & lt; Algorithm & gt; # Include & lt; Iostream & gt; Structure A {A}: _ x (42) {} A (double x): _ x (x) {} double _ x; }; Structure factory {one operator () () {return A (3.14); }}; Int main () {std :: vector & lt; A & gt; V; Int nbr = 3; V.reserve (NBR); Std :: generate_n (v.begin (), NBR, Factory ()); Std :: cout & lt; & Lt; "Good value" & lt; & Lt; Std :: endl; For (int i = 0; i   

thanks :)

Either understand me enough Your concern does not come, or you have misled the resize () does not modify any existing elements in the container (except if you are in small size size, except for removal).

Now, your real problem is that you have an undefined behavior in your program in vector capacity () == NBR , but size () == 0 < / Code> When you call gener_n , and it's writting after the end is witting. There are two solutions for this, first you first calling gener_n :

  std :: vector & lt; A & gt; V; Int nbr = 3; V.resize (NBR); Std :: generate_n (v.begin (), NBR, Factory ());   

Or you can change the type of iterator:

  std :: vector & lt; A & gt; V; Int nbr = 3; V.reserve (NBR); Std :: generate_n (std :: back_inserter (v), nbr, factory ());    

Comments