I want to use a factory function for my vector and also use the iterators without calling resize which blows my previous values ?
Is it possible or am I missing a point in STL design ?
#include <vector>
#include <algorithm>
#include <iostream>
struct A
{
A():_x(42){}
A(double x):_x(x){}
double _x;
};
struct factory
{
A operator()()
{
return A(3.14);
}
};
int main()
{
std::vector<A> v;
int nbr = 3;
v.reserve(nbr);
std::generate_n(v.begin(), nbr, factory());
std::cout << "Good values" << std::endl;
for(int i = 0 ; i < nbr ; ++i)
std::cout << v[i]._x << std::endl;
v.resize(nbr); //How I can have the syntax below without the resize which blows my previous values ?
std::cout << "resize has been called so values are bad (i.e default ctor)" << std::endl;
for(std::vector<A>::iterator it = v.begin() ; it != v.end() ; ++it)
std::cout << (*it)._x << std::endl;
}
Thanks 🙂
Either I did not quite understand your concern, or else you have been mislead.
resize()does not modify any of the existing elements in the container (other than those removed if you resize to a smaller size).Now, your actual problem is that you have undefined behavior in your program. The vector has
capacity() == nbrbutsize() == 0when you callgenerate_n, and that is writting beyond the end of the container. There are two solutions for this, first you can resize before callinggenerate_n:Or else you can change the type of the iterator: